Exemplo n.º 1
0
        public ItemToolbar(DynamicEntity dynamicEntity, string actions = null, string newType = null, object prefill = null, object toolbar = null, object settings = null)
        {
            _fullSettings = settings;

            if (toolbar != null)
            {
                // check conflicting parameters
                if (actions != null || newType != null || prefill != null)
                    throw new Exception(
                        "trying to build toolbar but got both toolbar and actions/prefill/newType - this is conflicting, cannot continue");
                _fullConfig = toolbar;
            }
            else // build a toolbar based on the actions or just from empty definition
            {
                if (actions == null)
                    _actions.Add(new ItemToolbarAction(dynamicEntity) {contentType = newType, prefill = prefill});
                else
                {
                    var actList = actions.Split(',').Select(p => p.Trim()).ToList();
                    foreach (string act in actList)
                        _actions.Add(new ItemToolbarAction(dynamicEntity)
                        {
                            action = act,
                            contentType = newType,
                            prefill = prefill
                        });
                }
            }
        }
    public void NHibernateShouldBeAbleToPersistCurrency()
    {
        dynamic currency = new DynamicEntity("Currency");

        currency.ISOCode                   = "GBP";
        currency.EnglishName               = "United Kingdom Pound";
        currency.ExchangeRateEURtoCurrency = 0.87780;
        currency.ExchangeRateUpdatedOn     = DateTime.UtcNow;
        currency.IsEnabled                 = true;
        currency.Symbol                    = null;

        Object id;

        using (var tx = Session.BeginTransaction())
        {
            id = Session.Save(currency.Name, currency.Map);
            tx.Commit();

            Assert.NotNull(id);
        }

        Session.Clear();

        using (var tx = Session.BeginTransaction())
        {
            var loadedCurrency = Session.Load(currency.Name, id);
            tx.Commit();

            Assert.NotNull(loadedCurrency);
        }

        Session.Flush();
    }
    public void GetPropertyWorks()
    {
        dynamic currency = new DynamicEntity("Currency");

        currency.ExchangeRateUpdatedOn = DateTime.UtcNow;
        Assert.NotNull(currency.ExchangeRateUpdatedOn);
    }
 public DynamicEntityPropertyAccess(string name, DynamicEntity entity, int repeaterIndex = -1, int repeaterTotal = -1)
 {
     Name = name;
     _entity = entity;
     RepeaterIndex = repeaterIndex;
     RepeaterTotal = repeaterTotal;
 }
Exemplo n.º 5
0
        internal static string Render(DynamicEntity parent, string entityField, string textTemplate)
        {
            // do basic checking
            if (!InlineCbDetector.IsMatch(textTemplate))
                return textTemplate;

            var result = new StringBuilder();
            var charProgress = 0;

            var matches = InlineCbDetector.Matches(textTemplate);
            if (matches.Count == 0)
                return textTemplate;

            // create edit-object which is necessary for context attributes
            var edit = new InPageEditingHelper(parent.SxcInstance);

            foreach (Match curMatch in matches)
            {
                // Get characters before the first match
                if (curMatch.Index > charProgress)
                    result.Append(textTemplate.Substring(charProgress, curMatch.Index - charProgress));
                charProgress = curMatch.Index + curMatch.Length;

                // get the infos we need to retrieve the value, get it.
                var marker = curMatch.Value.Replace("\'", "\"");

                if (marker.IndexOf("sxc=\"sxc-content-block\"", StringComparison.Ordinal) == 0)
                    continue;

                var guidMatch = GuidExtractor.Match(marker);
                var likelyGuid = guidMatch.Groups[1].Value;

                // check if guid is valid
                Guid guid;
                if (!Guid.TryParse(likelyGuid, out guid))
                    continue;

                object objFound;
                DynamicEntity subitem = null;
                var found = parent.TryGetMember(entityField, out objFound);

                if (found)
                {
                    var itms = (IList<DynamicEntity>)objFound;
                    if (itms?.Count > 0)
                        subitem = itms.FirstOrDefault(i => i.EntityGuid == guid);
                }

                result.Append(Simple.RenderWithEditContext(parent, subitem, entityField,  guid, edit));
            }

            // attach the rest of the text (after the last match)
            result.Append(textTemplate.Substring(charProgress));

            // Ready to finish, but first, ensure repeating if desired
            var finalResult = result.ToString();
            return finalResult;
        }
    public void SetPropertyWorks()
    {
        dynamic currency = new DynamicEntity("Currency");

        currency.IsEnabled = true;
        Assert.True(currency.IsEnabled);

        currency.IsEnabled = false;
        Assert.False(currency.IsEnabled);
    }
Exemplo n.º 7
0
Arquivo: Simple.cs Projeto: 2sic/2sxc
        internal static string RenderWithEditContext(DynamicEntity parent, DynamicEntity subItem, string cbFieldName,  Guid? newGuid = null, IInPageEditingSystem edit = null)
        {
            if (edit == null)
                edit = new InPageEditingHelper(parent.SxcInstance);

            var attribs = edit.ContextAttributes(parent, field: cbFieldName, newGuid: newGuid);
            var inner = (subItem == null) ? "": Render(parent.SxcInstance.ContentBlock, subItem.Entity).ToString();
            var cbClasses = edit.Enabled ? WrapperSingleItem : "";
            return string.Format(WrapperTemplate, new object[] { cbClasses, attribs, inner});
        }
Exemplo n.º 8
0
Arquivo: Render.cs Projeto: 2sic/2sxc
        /// <summary>
        /// Render content-blocks into a larger html-block containing placeholders
        /// </summary>
        /// <param name="context">The parent-item containing the content-blocks and providing edit-context</param>
        /// <param name="dontRelyOnParameterOrder"></param>
        /// <param name="field">Field containing the content-blocks</param>
        /// <param name="merge">Optional: html-text containing special placeholders</param>
        /// <returns></returns>
        public static IHtmlString All(DynamicEntity context,
            string dontRelyOnParameterOrder = Constants.RandomProtectionParameter,
            string field = null, 
            string merge = null)
        {
            Constants.ProtectAgainstMissingParameterNames(dontRelyOnParameterOrder, "All");
            if (field == null)
                throw new ArgumentNullException(nameof(field));

            return (merge == null)
                ? new HtmlString(Simple.RenderListWithContext(context, field))
                : new HtmlString(InTextContentBlocks.Render(context, field, merge));
        }
Exemplo n.º 9
0
Arquivo: Render.cs Projeto: 2sic/2sxc
        /// <summary>
        /// Render one content block
        /// This is accessed through DynamicEntity.Render()
        /// At the moment it MUST stay internal, as it's not clear what API we want to surface
        /// </summary>
        /// <param name="context">The parent-item containing the content-blocks and providing edit-context</param>
        /// <param name="dontRelyOnParameterOrder"></param>
        /// <param name="item">The content-block item to render</param>
        /// <param name="field">Optional: </param>
        /// <param name="newGuid"></param>
        /// <returns></returns>
        public static IHtmlString One(DynamicEntity context,
            string dontRelyOnParameterOrder = Constants.RandomProtectionParameter,
            DynamicEntity item = null, 
            string field = null,
            Guid? newGuid = null)
        {
            Constants.ProtectAgainstMissingParameterNames(dontRelyOnParameterOrder, "One");
            if (item == null)
                item = context;

            return field == null
                ? Simple.Render(context.SxcInstance.ContentBlock, item.Entity)
                : new HtmlString(Simple.RenderWithEditContext(context, item, field, newGuid));
        }
Exemplo n.º 10
0
 public void ReadElement(DynamicEntity doc)
 {
     sbyte typeNum = (sbyte)reader.ReadByte();
     position++;
     String key = ReadString();
     if (key == "$id")
         doc.Id = ReadElementType(typeNum) as string;
     else if (key == "$ref")
     {
         doc.Type = ReadElementType(typeNum) as string;
     }
     else
         doc.Add(key, ReadElementType(typeNum));
 }
Exemplo n.º 11
0
        public HtmlString Toolbar(DynamicEntity target = null,
            string dontRelyOnParameterOrder = Constants.RandomProtectionParameter, 
            string actions = null,
            string contentType = null, 
            object prefill = null,
            object toolbar = null,
            object settings = null)
        {
            if (!Enabled) return null;
            Constants.ProtectAgainstMissingParameterNames(dontRelyOnParameterOrder, "Toolbar");

            var itmToolbar = new ItemToolbar(target, actions, contentType, prefill, toolbar, settings);

            return new HtmlString(itmToolbar.Toolbar);
        }
Exemplo n.º 12
0
        public HtmlString ContextAttributes(DynamicEntity target,
            string dontRelyOnParameterOrder = Constants.RandomProtectionParameter, 
            string field = null,
            string contentType = null, 
            Guid? newGuid = null)
        {
            if (!Enabled) return null;
            Constants.ProtectAgainstMissingParameterNames(dontRelyOnParameterOrder, "ContextAttributes");

            if(field == null) throw new Exception("need parameter field");

            return new HtmlString(string.Format(
                _jsonTemplate, 
                target.EntityId, 
                field,
                contentType ?? Settings.AttributeSetStaticNameContentBlockTypeName,
                newGuid));
        }
Exemplo n.º 13
0
        public ItemToolbarAction(DynamicEntity dynamicEntity = null)
        {
            // a null value/missing is also valid, when all you want is a new/add toolbar
            if (dynamicEntity == null)
                return;

            var Entity = dynamicEntity.Entity;
            isPublished = Entity.IsPublished;
            var editingData = Entity as IHasEditingData;
            if (editingData != null)
            {
                sortOrder = editingData.SortOrder;
                useModuleList = true;
            }
            else
            {
                entityId = Entity.EntityId;
                contentType = Entity.Type.Name;
            }
        }
Exemplo n.º 14
0
        private void bwUpdateConfig_DoWork(object sender, DoWorkEventArgs e)
        {
            dynamic d = new DynamicEntity(Param.ShopId, "Config");
            d.Value = JsonConvert.SerializeObject(Param.SystemConfig);
            var azureTable = Param.AzureTableClient.GetTableReference("Shop");
            TableBatchOperation batchOperation = new TableBatchOperation();
            batchOperation.InsertOrMerge(d);
            azureTable.ExecuteBatch(batchOperation);

            d = new DynamicEntity(Param.ShopId, Param.LicenseKey);
            d.DevicePrinter = Param.DevicePrinter;
            azureTable = Param.AzureTableClient.GetTableReference("ShopApplication");
            batchOperation = new TableBatchOperation();
            batchOperation.InsertOrMerge(d);
            azureTable.ExecuteBatch(batchOperation);

            Properties.Settings.Default.DevicePrinter = Param.DevicePrinter;
            Properties.Settings.Default.Save();
            Properties.Settings.Default.Upgrade();
        }
Exemplo n.º 15
0
 public Entity ReadEntity()
 {
     int startpos = position;
     DynamicEntity doc = new DynamicEntity();
     int size = reader.ReadInt32();
     position += 4;
     while ((position - startpos) + 1 < size)
     {
         ReadElement(doc);
     }
     byte eoo = reader.ReadByte();
     position++;
     if (eoo != 0)
         throw new InvalidDataException("Document not null terminated");
     if (size != position - startpos)
     {
         throw new InvalidDataException(string.Format("Should have read {0} bytes from stream but only read {1}", size, (position - startpos)));
     }
     return doc;
 }
Exemplo n.º 16
0
        public Program()
        {
            m_service = new MockCrmService();
            contact contact = new contact();
            contact.address1_name = "Dan";
            contact.address1_city = "Bethesda";
            Guid id = m_service.Create( contact );

            // data for testing links
            subject subject1 = new subject();
            subject1.title = "parent";
            Guid subject1ID = m_service.Create( subject1 );
            subject subject2 = new subject();
            subject2.title = "child";
            subject2.parentsubject = new Lookup( "subject", subject1ID );
            m_service.Create( subject2 );

            DynamicEntity de = new DynamicEntity();
            de.Name = "mydynamic";
            de.Properties.Add( new StringProperty( "prop1", "foo" ) );
            Guid deID = m_service.Create( de );
        }
Exemplo n.º 17
0
Arquivo: Simple.cs Projeto: 2sic/2sxc
        internal static string RenderListWithContext(DynamicEntity parent, string fieldName, IInPageEditingSystem edit = null)
        {
            object objFound;
            var innerBuilder = new StringBuilder();
            var found = parent.TryGetMember(fieldName, out objFound);
            if (found)
            {
                var itms = objFound as IList<DynamicEntity>;
                if(itms != null)
                    foreach (var cb in itms)
                        innerBuilder.Append(Render(cb.SxcInstance.ContentBlock, cb.Entity));
            }

            // create edit object if missing...to re-use in the wh
            if (edit == null)
                edit = new InPageEditingHelper(parent.SxcInstance);

            return string.Format(WrapperTemplate, new object[]
            {
                edit.Enabled ? WrapperMultiItems : "",
                edit.ContextAttributes(parent, field: fieldName),
                innerBuilder
            });
        }
Exemplo n.º 18
0
        //保存
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            StringBuilder error = new StringBuilder();

            if (!Util.CheckOperationSafe())
            {
                return;
            }

            //取值
            this.bindingControl.CollectData();
            DynamicEntity entity = (DynamicEntity)this.bindingControl.Data;

            PropertyValueCollection pvc = JSONSerializerExecute.Deserialize <PropertyValueCollection>(Request.Form.GetValue("properties", string.Empty));

            entity.Properties.FromPropertyValues(pvc);

            //检查重复项
            entity.Fields.GroupBy(p => p.Name).ForEach(p => { if (p.Count() > 1)
                                                              {
                                                                  error.Append(p.Key + "有重复项!\r\n");
                                                              }
                                                       });

            bool needCheckExist = false;

            #region
            if (DESchemaObjectAdapter.Instance.Exist(entity.ID, DateTime.Now.SimulateTime()))
            {
                //更新实体
                DynamicEntity old = DESchemaObjectAdapter.Instance.Load(entity.ID, DateTime.Now.SimulateTime()) as DynamicEntity;
                if (!old.Name.Equals(entity.Name))
                {
                    needCheckExist = true;
                }
            }
            else
            {
                needCheckExist = true;
            }


            if (needCheckExist)
            {
                //生成CodeName
                entity.BuidCodeName();

                if (DEDynamicEntityAdapter.Instance.ExistByCodeName(entity.CodeName, DateTime.Now.SimulateTime()))
                {
                    error.AppendFormat("已存在名称为[{0}]的实体!\r\n", entity.Name);
                }
            }

            (error.Length > 0).TrueThrow(error.ToString());
            #endregion
            //入库
            DEObjectOperations.InstanceWithPermissions.DoOperation(this.OperationMode, entity, null);
            if (entity.SnapshotTable.IsNotEmpty())
            {
                if (this.OperationMode == SCObjectOperationMode.Add)
                {
                    INVDynamicEntitySnapshotAdapter.Instance.CreateSnapshot(entity);
                }
                else if (this.OperationMode == SCObjectOperationMode.Update)
                {
                    INVDynamicEntitySnapshotAdapter.Instance.UpdateSnapshot(entity);
                }
            }
            entity.ClearCacheData();
            this.HFEntityID.Value   = entity.ID;
            this.HFEntityName.Value = entity.Name;
            if (this.OperationType.Equals("1"))
            {
                HttpContext.Current.Response.Write("<script>window.returnValue=true;window.close()</script>");
                WebUtility.RefreshParentWindow("close", RefreshParentWindowName.Parent);
            }
            else
            {
                WebUtility.RefreshParentWindow("close", RefreshParentWindowName.Parent);
                Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "", string.Format("top.setEntityInfo('{0}','{1}');", entity.ID, entity.Name), true);
            }
        }
Exemplo n.º 19
0
    public void InstantiateIn(Control container)
    {
        HtmlGenericControl div = new HtmlGenericControl("div");
          div.InnerText = "sample text, other controls";
          container.Controls.Add(div);

          DynamicEntity de = new DynamicEntity();
          container.Controls.Add(de);
    }
 public AbstractEntityController(DynamicEntity e)
 {
     this.ent = e;
 }
Exemplo n.º 21
0
 public void Replace(DynamicEntity entity, DateTime now)
 {
     TimeStamp = now.ToTimeStampString();
     entity.UpdateTimeStamp(TimeStamp);
     Data = entity.AsDbRowJson();
 }
Exemplo n.º 22
0
        public SaleOrderEntityChild_T_ZR5_SS02P_RFC()
        {
            DynamicEntity entity = DEDynamicEntityAdapter.Instance.LoadByCodeName("/集团公司/销售板块/销售订单/T_ZR5_SS02P") as DynamicEntity;

            _instance = entity.CreateInstance();
        }
Exemplo n.º 23
0
        internal static string Render(DynamicEntity parent, string entityField, string textTemplate)
        {
            // do basic checking
            if (!InlineCbDetector.IsMatch(textTemplate))
            {
                return(textTemplate);
            }

            var result       = new StringBuilder();
            var charProgress = 0;

            var matches = InlineCbDetector.Matches(textTemplate);

            if (matches.Count == 0)
            {
                return(textTemplate);
            }

            // create edit-object which is necessary for context attributes
            var edit = new InPageEditingHelper(parent.SxcInstance, parent.SxcInstance.Log);

            foreach (Match curMatch in matches)
            {
                // Get characters before the first match
                if (curMatch.Index > charProgress)
                {
                    result.Append(textTemplate.Substring(charProgress, curMatch.Index - charProgress));
                }
                charProgress = curMatch.Index + curMatch.Length;

                // get the infos we need to retrieve the value, get it.
                var marker = curMatch.Value.Replace("\'", "\"");

                if (marker.IndexOf("sxc=\"sxc-content-block\"", StringComparison.Ordinal) == 0)
                {
                    continue;
                }

                var guidMatch  = GuidExtractor.Match(marker);
                var likelyGuid = guidMatch.Groups[1].Value;

                // check if guid is valid
                if (!Guid.TryParse(likelyGuid, out var guid))
                {
                    continue;
                }

                DynamicEntity subitem = null;
                var           found   = parent.TryGetMember(entityField, out var objFound);

                if (found)
                {
                    var itms = (IList <DynamicEntity>)objFound;
                    if (itms?.Count > 0)
                    {
                        subitem = itms.FirstOrDefault(i => i.EntityGuid == guid);
                    }
                }

                result.Append(Simple.RenderWithEditContext(parent, subitem, entityField, guid, edit));
            }

            // attach the rest of the text (after the last match)
            result.Append(textTemplate.Substring(charProgress));

            // Ready to finish, but first, ensure repeating if desired
            var finalResult = result.ToString();

            return(finalResult);
        }
        /// <summary>
        /// Converts the contact into the user.
        /// </summary>
        /// <param name="contact">The contact.</param>
        /// <returns>The user.</returns>
        public CRMUser Convert(DynamicEntity contact)
        {
            Assert.ArgumentNotNull(contact, "contact");

            var nameProperty = (StringProperty)contact.Properties.ByName(Configuration.Settings.UniqueKeyProperty);
            var keyProperty  = (KeyProperty)contact.Properties.ByName("contactid");

            var emailProperty = contact.Properties.ByName("emailaddress1") as StringProperty;

            emailProperty = emailProperty ?? new StringProperty
            {
                Name  = "emailaddress1",
                Value = String.Empty
            };

            var descriptionProperty = contact.Properties.ByName("description") as StringProperty;

            descriptionProperty = descriptionProperty ?? new StringProperty
            {
                Name  = "description",
                Value = String.Empty
            };

            var createdProperty = contact.Properties.ByName("createdon") as CrmDateTimeProperty;

            createdProperty = createdProperty ?? new CrmDateTimeProperty
            {
                Name  = "createdon",
                Value = new CrmDateTime {
                    Value = DateTime.MinValue.ToString()
                }
            };

            var lastActivityDateProperty = contact.Properties.ByName("lastusedincampaign") as CrmDateTimeProperty;

            lastActivityDateProperty = lastActivityDateProperty ?? new CrmDateTimeProperty
            {
                Name  = "lastusedincampaign",
                Value = new CrmDateTime {
                    Value = DateTime.MinValue.ToString()
                }
            };

            var user = new CRMUser(
                nameProperty.Value,
                keyProperty.Value.Value,
                emailProperty.Value,
                null,
                descriptionProperty.Value,
                true,
                false,
                DateTime.Parse(createdProperty.Value.Value),
                DateTime.Now,
                DateTime.Parse(lastActivityDateProperty.Value.Value),
                DateTime.MinValue,
                DateTime.MinValue);

            var propertyToValueConverter = new PropertyToValueConverterV3();

            foreach (var property in contact.Properties)
            {
                user.SetPropertyValue(property.Name, propertyToValueConverter.Convert(property));
            }

            return(user);
        }
Exemplo n.º 25
0
        private static void OnImport(IStartAddin msg)
        {
            //StatusModel.Timer("Importing Documents");
            //import asycuda xml id and details
            if (msg.Entity == null || msg.Entity.Id == 0)
            {
                MessageBox.Show("Please Select Asycuda Document Set");
                return;
            }


            var od = new OpenFileDialog();

            od.DefaultExt  = ".xml";
            od.Filter      = "Xml Documents (.xml)|*.xml";
            od.Multiselect = true;
            var result = od.ShowDialog();

            if (result == true)
            {
                //StatusModel.Timer(string.Format("Importing {0} files", od.FileNames.Count()));
                //StatusModel.StartStatusUpdate("Importing files", od.FileNames.Count());
                //StatusModel.RefreshNow();
                foreach (var f in od.FileNames)
                {
                    if (ASYCUDA.CanLoadFromFile(f))
                    {
                        var a   = Asycuda421.ASYCUDA.LoadFromFile(f);
                        var res = AsycudaToDataBase421.Instance.Import(a, msg.Entity);
                        var de  = new DynamicEntity(
                            new DynamicEntityType("xcuda_ASYCUDA", "xcuda_ASYCUDA",
                                                  new List <IEntityKeyValuePair>(), new Dictionary <string, List <dynamic> >(),
                                                  new ObservableDictionary <string, Dictionary <int, dynamic> >(),
                                                  new List <IDynamicRelationshipType>(), new List <IDynamicRelationshipType>(),
                                                  DynamicEntityType.NullEntityType(),
                                                  new ObservableList <IAddinAction>()), 0,
                            new Dictionary <string, object>());

                        EventMessageBus.Current.Publish(new UpdateEntityWithChanges(de,
                                                                                    res.Properties.ToDictionary(x => x.Key, x => x.Value),
                                                                                    new StateCommandInfo(msg.Process,
                                                                                                         RevolutionData.Context.CommandFunctions.UpdateCommandData(de.EntityType.Name,
                                                                                                                                                                   RevolutionData.Context.Entity.Commands.CreateEntity)), msg.Process, Source));
                    }
                    else
                    {
                        throw new ApplicationException(string.Format("Can not Load file '{0}'", f));
                    }
                }

                var cnt = od.FileNames.Length;
                var t   = 0;
                EventMessageBus.Current.GetEvent <IEntityWithChangesUpdated>(
                    new StateEventInfo(msg.Process, Entity.Events.EntityUpdated), Source)
                .Where(x => x.EntityType.Name == "xcuda_ASYCUDA" && x.Process.Id == msg.Process.Id)
                .Subscribe(x =>
                {
                    t += 1;
                    if (t == cnt)
                    {
                        MessageBox.Show("Complete");
                    }
                });


                //StatusModel.StopStatusUpdate();
            }
            // StatusModel.StopStatusUpdate();
        }
Exemplo n.º 26
0
        /// <summary>
        /// 创建主表测试数据,无子表
        /// </summary>
        /// <returns></returns>
        private static DynamicEntity CreateDemoHeaderEntity()
        {
            DynamicEntity SaleOrderItem = new DynamicEntity();

            SaleOrderItem.ID          = Guid.NewGuid().ToString();
            SaleOrderItem.Name        = "销售单明细";
            SaleOrderItem.Description = "销售单明细";
            SaleOrderItem.CategoryID  = Define.TestCategoryID;  //集团公司/管道板块/运输
            SaleOrderItem.BuidCodeName();
            SaleOrderItem.SortNo     = 1;
            SaleOrderItem.CreateDate = DateTime.Now;

            DynamicEntity saleOrderEntityItem1 = CreateDemoItemEntity("第一个");
            DynamicEntity saleOrderEntityItem2 = CreateDemoItemEntity("第二个");

            SaleOrderItem.Fields.Add(new DynamicEntityField()
            {
                ID         = Guid.NewGuid().ToString(),
                Name       = "物料名称",
                FieldType  = FieldTypeEnum.String,
                Length     = 255,
                SortNo     = 0,
                CreateDate = SaleOrderItem.CreateDate
            });
            SaleOrderItem.Fields.Add(new DynamicEntityField()
            {
                ID        = Guid.NewGuid().ToString(),
                Name      = "物料数量",
                FieldType = FieldTypeEnum.Int,
                Length    = 4,
                SortNo    = 1
            });
            SaleOrderItem.Fields.Add(new DynamicEntityField()
            {
                ID        = Guid.NewGuid().ToString(),
                Name      = "单价",
                FieldType = FieldTypeEnum.Decimal,
                Length    = 18,
                SortNo    = 2
            });

            SaleOrderItem.Fields.Add(new DynamicEntityField()
            {
                ID        = Guid.NewGuid().ToString(),
                Name      = "销售订单字表1",
                FieldType = FieldTypeEnum.Collection,
                ReferenceEntityCodeName = saleOrderEntityItem1.CodeName,
                Length = 50,
                SortNo = 3
            });

            SaleOrderItem.Fields.Add(new DynamicEntityField()
            {
                ID        = Guid.NewGuid().ToString(),
                Name      = "销售订单字表2",
                FieldType = FieldTypeEnum.Collection,
                ReferenceEntityCodeName = saleOrderEntityItem2.CodeName,
                Length = 18,
                SortNo = 4
            });

            DEObjectOperations.InstanceWithoutPermissions.AddEntity(SaleOrderItem);

            return(SaleOrderItem);
        }
 public UnderwaterNewtonEntityController(DynamicEntity e)
     : base(e)
 {
     Gravity_Acc = UNDERWATER_GRAVITY_ACCELERATION;
     Gravity_Max = UNDERWATER_GRAVITY_MAX;
 }
Exemplo n.º 28
0
        private OGM ReadNode(OGM parent, Entity targetEntity, RawNode node)
        {
            object?keyObject = null;

            if (targetEntity.Key != null)
            {
                node.Properties.TryGetValue(targetEntity.Key.Name, out keyObject);
            }

            string?typeName = null;

            if (targetEntity.NodeType != null)
            {
                object?nodeType;
                if (node.Properties.TryGetValue(targetEntity.NodeType.Name, out nodeType))
                {
                    typeName = nodeType as string;
                }
            }

            if (typeName == null)
            {
                if (!targetEntity.IsAbstract)
                {
                    typeName = targetEntity.Name;
                }
                else
                {
                    typeName = targetEntity.GetConcreteClasses().Where(e => node.Labels.Contains(e.Label.Name)).Select(e => e.Name).FirstOrDefault();
                }
            }

            if (typeName == null)
            {
                throw new NotSupportedException("The concrete type of the node could not be determined.");
            }

            OGM?item = null;

            if (keyObject != null)
            {
                item = Transaction.RunningTransaction.GetEntityByKey(typeName, keyObject);
                if (item != null &&
                    (item.PersistenceState == PersistenceState.HasUid
                     ||
                     item.PersistenceState == PersistenceState.Loaded))
                {
#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
                    item.SetData(node.Properties);
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
                    item.PersistenceState = PersistenceState.Loaded;
                }

                if (item == null)
                {
                    if (targetEntity.Parent.IsUpgraded)
                    {
                        Type type = typeCache.TryGetOrAdd(typeName, key =>
                        {
                            type = parent.GetType().Assembly.GetTypes().FirstOrDefault(x => x.Name == typeName);
                            if (type == null)
                            {
                                throw new NotSupportedException();
                            }

                            return(type);
                        });
                        item = (OGM)Activator.CreateInstance(type) !;
                    }
                    else
                    {
                        item = new DynamicEntity(targetEntity, Parser.ShouldExecute);
                    }

#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
                    item.SetData(node.Properties);
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
                    item.SetKey(keyObject);
                    item.PersistenceState = PersistenceState.Loaded;
                }
            }

            if (item is null)
            {
                throw new InvalidOperationException("Could not load object from node properties.");
            }

            return(item);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Client:
 ///     Handles any additional usage stuff. When this is called, it is to be assumed that the Server has recognized
 ///     the IUsableEntity as having been successfully used.
 /// Server:
 ///     Attempts to use this IUsableEntity on the <paramref name="charEntity"/>.
 /// </summary>
 /// <param name="charEntity">CharacterEntity that is trying to use this IUsableEntity. Can be null.</param>
 /// <returns>True if this IUsableEntity was successfully used, else false. On the Client, this is generally
 /// unused.</returns>
 public abstract bool Use(DynamicEntity charEntity);
Exemplo n.º 30
0
        private void SalvarRelacionamentoNoEMS(string action, string xmlIntegrationLog, DynamicEntity entity)
        {
            Guid relacionamentoId = Guid.Empty;

            if (entity.Properties.Contains("new_relacionamentoid"))
            {
                relacionamentoId = ((Key)entity.Properties["new_relacionamentoid"]).Value;
            }

            IntegrarService      integrarRelacionamento = new IntegrarService();
            MensagemDeRetornoEMS mensagemRetorno        = new MensagemDeRetornoEMS();

            mensagemRetorno = integrarRelacionamento.Integrar("new_relacionamento", action, xmlIntegrationLog, relacionamentoId);

            Relacionamento relacionamento = new Relacionamento();

            relacionamento.Id = relacionamentoId;
            relacionamento.DescricaoDaMensagemDeIntegracao = mensagemRetorno.Descricao;
            relacionamento.CodigoEms          = mensagemRetorno.CodigoEMS;
            relacionamento.StatusDaIntegracao = mensagemRetorno.StatusIntegracao;
            relacionamento.ExportaERP         = "";

            DomainService.RepositoryCliente.AtualizarRelacionamento(relacionamento);
        }
Exemplo n.º 31
0
        public void Send(string organizationName, string type, string xmlIntegration, DynamicEntity entity, IPluginExecutionContext context)
        {
            try
            {
                if (string.IsNullOrEmpty(xmlIntegration))
                {
                    return;
                }

                organizacao = new Organizacao(organizationName);

                switch (entity.Name)
                {
                case "account":
                    SalvarClienteNoEMS(type, xmlIntegration, entity);
                    break;

                case "contact":
                    SalvarContatoNoEMS(type, xmlIntegration, context);
                    break;

                case "customeraddress":
                    SalvarEnderecoNoEMS(type, xmlIntegration, entity);
                    break;

                case "new_relacionamento":
                    SalvarRelacionamentoNoEMS(type, xmlIntegration, entity);
                    break;
                }
            }
            catch (Exception ex) { LogService.GravaLog(ex, TipoDeLog.PluginIntegradorERP); }
        }
Exemplo n.º 32
0
    /// <summary>
    /// Set field value
    /// </summary>
    /// <param name="DynamicEntityObject">DynamicEntity</param>
    /// <param name="service">MetadataService</param>
    /// <param name="AttributeType">Type of attribute</param>
    /// <param name="AttributeName">Attribute name</param>
    /// <param name="AttributeValue1">Attribute first value</param>
    /// <param name="AttributeValue2">Attribute first value</param>
    /// <returns></returns>
    public static bool SetFieldValue(this DynamicEntity DynamicEntityObject, MetadataService service, String AttributeType, string AttributeName, String AttributeValue1, String AttributeValue2)
    {
        //bool ret = false;
        string TypeOfAttribute;    // = null;

        try
        {
            //$ when the
            if (DynamicEntityObject.Properties.Contains(AttributeName))
            {
                TypeOfAttribute = DynamicEntityObject.Properties[AttributeName].GetType().Name;
            }
            else
            {
                //TODO: replace this function with meta data service
                TypeOfAttribute = RetrieveAttributeMetadata(service, DynamicEntityObject.Name, AttributeName);
            }


            if (TypeOfAttribute == null || TypeOfAttribute == "PrimaryKey")
            {
                return(false);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Owner" || TypeOfAttribute == "Owner")
            {
                DynamicEntityObject[AttributeName] = new Lookup(AttributeValue1, new Guid(AttributeValue2));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Customer" || TypeOfAttribute == "Customer")
            {
                DynamicEntityObject[AttributeName] = new Customer(AttributeValue1, new Guid(AttributeValue2));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.CrmDateTime" || TypeOfAttribute == "CrmDateTime" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.DateTimeAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new CrmDateTime(AttributeValue1);
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.CrmBoolean" || TypeOfAttribute == "CrmBoolean" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.BooleanAttributeMetadata")
            {
                DynamicEntityObject.Properties[AttributeName] = new CrmBoolean(bool.Parse(AttributeValue1));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.String" || TypeOfAttribute == "String" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.StringAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = (string)AttributeValue1;
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Lookup" || TypeOfAttribute == "Lookup" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.LookupAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new Lookup(AttributeValue1, new Guid(AttributeValue2));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.Picklist" || TypeOfAttribute == "Picklist" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.PicklistAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new Picklist(int.Parse(AttributeValue1));
                return(true);
            }
            else if (TypeOfAttribute == "Microsoft.Crm.Sdk.CrmNumber" || TypeOfAttribute == "CrmNumber" || TypeOfAttribute == "Integer" || TypeOfAttribute == "Microsoft.Crm.Sdk.Metadata.IntegerAttributeMetadata")
            {
                DynamicEntityObject[AttributeName] = new CrmNumber(int.Parse(AttributeValue1));
                return(true);
            }
        }
        catch (SoapException sopEx)
        {
            throw;
        }

        return(false);
    }
    public void GetMapWorks()
    {
        dynamic currency = new DynamicEntity("Currency");

        Assert.Equal(typeof(Dictionary<String, Object>), currency.Map.GetType());
    }
 internal DictionaryPropertyDescriptor(DynamicEntity d, string key)
     : base(key.ToString(), null)
 {
     _dynamic = d;
     _key = key;
 }
Exemplo n.º 35
0
 public override int GetHashCode()
 {
     return(DynamicEntity.GetHashCode());
 }
Exemplo n.º 36
0
 public void OnPost(EntityModel entity)
 {
     DynamicEntity d = DynamicEntity.CreateFromObject(entity);
 }
Exemplo n.º 37
0
        public SaleOrderEntityMain_RFC()
        {
            DynamicEntity entity = DEDynamicEntityAdapter.Instance.LoadByCodeName("/集团公司/销售板块/销售订单/ZR5_SDIF_MH003") as DynamicEntity;

            _instance = entity.CreateInstance();
        }
Exemplo n.º 38
0
        public void Execute(IPluginExecutionContext context)
        {
            try
            {
                DynamicEntity EntidadeDoContexto = null;
                if (context.InputParameters.Properties.Contains("Target") && context.InputParameters.Properties["Target"] is DynamicEntity)
                {
                    EntidadeDoContexto = context.InputParameters.Properties["Target"] as DynamicEntity;
                }

                if (EntidadeDoContexto == null)
                {
                    return;
                }

                if (EntidadeDoContexto.Properties.Contains("new_linha_unidade_negocioid") || EntidadeDoContexto.Properties.Contains("new_produtoid"))
                {
                    DynamicEntity preImage = null;
                    if (context.PreEntityImages.Contains("preImage"))
                    {
                        preImage = (DynamicEntity)context.PreEntityImages["preImage"];
                    }
                    if (preImage == null)
                    {
                        return;
                    }

                    if (EntidadeDoContexto.Properties.Contains("new_linha_unidade_negocioid") && EntidadeDoContexto.Properties.Contains("new_produtoid"))
                    {
                        if (((Lookup)EntidadeDoContexto.Properties["new_linha_unidade_negocioid"]) == null && ((Lookup)EntidadeDoContexto.Properties["new_linha_unidade_negocioid"]) == null)
                        {
                            throw new InvalidPluginExecutionException("Ação não executada. É necessário o preenchimentos de Produto ou Segmento.");
                        }
                    }

                    if (EntidadeDoContexto.Properties.Contains("new_linha_unidade_negocioid"))
                    {
                        if (((Lookup)EntidadeDoContexto.Properties["new_linha_unidade_negocioid"]) == null)
                        {
                            if (!preImage.Properties.Contains("new_produtoid"))
                            {
                                throw new InvalidPluginExecutionException("Ação não executada. É necessário o preenchimentos de Produto ou Segmento.");
                            }
                        }
                    }

                    if (EntidadeDoContexto.Properties.Contains("new_produtoid"))
                    {
                        if (((Lookup)EntidadeDoContexto.Properties["new_produtoid"]) == null)
                        {
                            if (!preImage.Properties.Contains("new_linha_unidade_negocioid"))
                            {
                                throw new InvalidPluginExecutionException("Ação não executada. É necessário o preenchimentos de Produto ou Segmento.");
                            }
                        }
                    }
                }
            }
            catch (InvalidPluginExecutionException ex) { throw ex; }
            catch (Exception ex)
            {
                LogService.GravaLog(ex, TipoDeLog.PluginNew_valor_servico_posto, "Intelbras.Crm.Application.Plugin.new_valor_servico_posto.PreCreate");
                throw ex;
            }
        }
Exemplo n.º 39
0
        static void Main()
        {
            bool success = false;
            int contactId = 0;
            var contactIDs = new int[1];

            try
            {
                #region Setup the Eloqua service

                //var service = new EloquaInstance("TestInstance", "Webtrends\\eloqua.api", "fyG9e1opgc!");

                EloquaServiceClient service = new EloquaServiceClient();
                service.ClientCredentials.UserName.UserName = @"";
                service.ClientCredentials.UserName.Password = "";

                #endregion

                #region Create a contact using a Dynamic Entity

                // Build a Contact Entity Type object
                EntityType entityType = new EntityType { ID = 0, Name = "Contact", Type = "Base" };

                // Create an Array of Dynamic Entities
                DynamicEntity[] dynamicEntities = new DynamicEntity[1];

                // Create a new Dynamic Entity and add it to the Array of Entities
                dynamicEntities[0] = new DynamicEntity();
                dynamicEntities[0].EntityType = entityType;

                // Create a Dynamic Entity's Field Value Collection
                dynamicEntities[0].FieldValueCollection = new DynamicEntityFields();

                // Add the Contact's Email Address field to the Dynamic Entity’s field collection
                dynamicEntities[0].FieldValueCollection.Add("C_EmailAddress", "*****@*****.**");

                // Add the Contact's First Name field to the Dynamic Entity’s field collection
                dynamicEntities[0].FieldValueCollection.Add("C_FirstName", "Cloud");

                // Execute the request
                var result = service.Create(dynamicEntities);

                // Verify the status of each Contact Create request in the results
                foreach (CreateResult t in result)
                {
                    // Successfull requests return a positive integer value for ID
                    if (t.ID != -1)
                    {
                        contactId = t.ID;
                        success = true;
                    }
                    // Failed requests return a -1 integer value for ID
                    else
                    {
                        // Extract the Error Message and Error Code for each failed Create request
                        foreach (Error createError in t.Errors)
                        {
                            Console.WriteLine(String.Format("Code: {0}", createError.ErrorCode));
                            Console.WriteLine(String.Format("Message: {0}", createError.Message));
                        }
                    }
                }

                #endregion

                #region Retrieve the contact dynamically

                if (success)
                {
                    // Set the ID of the Contact Entity
                    contactIDs[0] = contactId;

                    // Create a new list containing the fields you want populated
                    List<string> fieldList = new List<string>();

                    // Add the Contact’s Email Address to the field list
                    fieldList.Add("C_EmailAddress");

                    // Add the Contact’s First Name to the field list
                    fieldList.Add("C_FirstName");

                    // Build a Dynamic Entity array to store the results
                    DynamicEntity[] retrievedEntities;

                    // If the field list is empty - the request will return all Entity Fields
                    // Otherwise, only fields defined in the field list are returned
                    if (fieldList.Count == 0)
                    {
                        // Execute the request and return all of the Entity's fields
                        retrievedEntities = service.Retrieve(entityType, contactIDs, null);
                    }
                    else
                    {
                        // Execute the request and return only the selected Entity fields
                        retrievedEntities = service.Retrieve(entityType, contactIDs, fieldList.ToArray());
                    }

                    // If a result was found, extract the field values for each Dynamic Entity
                    if (retrievedEntities.Length > 0)
                    {
                        foreach (DynamicEntity dynamicEntity in retrievedEntities)
                        {
                            // Extract the Field Name and Value for each element in the collection
                            foreach (KeyValuePair<string, string> keyValPair in dynamicEntity.FieldValueCollection)
                            {

                                Console.WriteLine("New Contact Created Successfully!");
                                Console.WriteLine(String.Format("Field Name: {0}", keyValPair.Key));
                                Console.WriteLine(String.Format("Field Value: {0}", keyValPair.Value));
                            }
                        }
                    }
                }
                #endregion

                // Customize your own error handling
            }
            catch (System.ServiceModel.FaultException ex)
            {
                // Catch Service Model Fault Exceptions
                Console.WriteLine(String.Format("Reson: {0}", ex.Reason.ToString()));
                Console.WriteLine(String.Format("Fault Type: {0}", ex.GetType().ToString()));
                Console.WriteLine(String.Format("Fault Code: {0}", ex.Code.Name.ToString()));
            }
            catch (Exception ex)
            {
                // Catch System Exceptions
                Console.WriteLine(String.Format("Exception Message: {0}", ex.Message.ToString()));
            }

            // Wait for user input before stepping out.
            Console.WriteLine("Press any key to continue.");
            Console.ReadKey();
        }
Exemplo n.º 40
0
 /// <summary>
 /// Return an object that represents an IDataStream, but is serializable
 /// </summary>
 public Dictionary <string, object> Prepare(DynamicEntity dynamicEntity)
 => GetDictionaryFromEntity(dynamicEntity.Entity);
Exemplo n.º 41
0
 public abstract void OnCollide(DynamicEntity collider);
Exemplo n.º 42
0
	    /// <summary>
	    /// Return an object that represents an IDataStream, but is serializable
	    /// </summary>
	    public Dictionary<string, object> Prepare(DynamicEntity dynamicEntity)
	        => GetDictionaryFromEntity(dynamicEntity.Entity);
Exemplo n.º 43
0
        public void BasicDynamicCRUDTest()
        {
            var fieldList = new List <FieldAttribute>();

            fieldList.Add(new FieldAttribute()
            {
                FieldName    = "ID",
                IsPrimaryKey = true,
                DataType     = System.Data.DbType.Int32
            });

            fieldList.Add(new FieldAttribute()
            {
                FieldName = "FirstName",
                DataType  = System.Data.DbType.String
            });

            fieldList.Add(new FieldAttribute()
            {
                FieldName   = "LastName",
                DataType    = System.Data.DbType.String,
                AllowsNulls = false
            });

            fieldList.Add(new FieldAttribute()
            {
                FieldName   = "DOB",
                DataType    = System.Data.DbType.DateTime,
                AllowsNulls = true
            });

            fieldList.Add(new FieldAttribute()
            {
                FieldName   = "ShiftStart",
                DataType    = System.Data.DbType.Time,
                AllowsNulls = true
            });

            var definition = new DynamicEntityDefinition("People", fieldList, KeyScheme.None);

            var store = GetTestStore();

            var exists = store.TableExists(definition.EntityName);

            if (exists)
            {
                store.DiscoverDynamicEntity("People");
                //                store.DropTable(definition.EntityName);
            }
            else
            {
                store.RegisterDynamicEntity(definition);
            }

            Assert.IsTrue(store.TableExists(definition.EntityName));

            var entity = new DynamicEntity("People");

            entity.Fields["id"]         = 1;
            entity.Fields["FirstName"]  = "John";
            entity.Fields["LastName"]   = "Doe";
            entity.Fields["DOB"]        = DBNull.Value;
            entity.Fields["ShiftStart"] = null;
            store.Insert(entity);

            entity = new DynamicEntity("People");
            entity.Fields["id"]         = 2;
            entity.Fields["FirstName"]  = "Jim";
            entity.Fields["LastName"]   = "Smith";
            entity.Fields["DOB"]        = null;
            entity.Fields["ShiftStart"] = DBNull.Value;
            store.Insert(entity);

            entity = new DynamicEntity("People");
            entity.Fields["id"]         = 3;
            entity.Fields["FirstName"]  = "Sam";
            entity.Fields["LastName"]   = "Adams";
            entity.Fields["DOB"]        = new DateTime(1776, 7, 4);
            entity.Fields["ShiftStart"] = new TimeSpan(17, 30, 0);
            store.Insert(entity);

            var items = store.Select("People");

            DumpData(items);

            store.Delete("People", items.First().Fields["ID"]);

            items = store.Select("People");
            DumpData(items);

            store.Delete("People", "LastName", "Smith");

            items = store.Select("People");
            DumpData(items);

            var person = items.First();

            person.Fields["FirstName"] = "Joe";
            person.Fields["LastName"]  = "Satriani";
            store.Update(person);

            items = store.Select("People");
            DumpData(items);

            // now let's change the structure and see what happens
            fieldList.Add(new FieldAttribute()
            {
                FieldName   = "Middle_Name",
                DataType    = System.Data.DbType.Double,
                AllowsNulls = true // this has to be true to add a column
            });

            var newDefinition = new DynamicEntityDefinition("People", fieldList, KeyScheme.Identity);

            store.RegisterDynamicEntity(newDefinition, true);

            items = store.Select("People");

            DumpData(items);
        }
Exemplo n.º 44
0
 public AbstractNewtonEntityController(DynamicEntity e)
     : base(e)
 {
     //--
 }
Exemplo n.º 45
0
 /// <summary>
 /// Provides an Adam instance for this item and field
 /// </summary>
 /// <param name="entity">The entity, often Content or similar</param>
 /// <param name="fieldName">The field name, like "Gallery" or "Pics"</param>
 /// <returns>An Adam object for navigating the assets</returns>
 public AdamNavigator AsAdam(DynamicEntity entity, string fieldName)
 => AppAndDataHelpers.AsAdam(AsEntity(entity), fieldName);
Exemplo n.º 46
0
        public void CopyEntityWithOutEntityMethodTest()
        {
            // /集团公司/管道板块/运输
            string categoryID = "48BE753C-630D-42F4-A02D-D2B50818F817";
            // /集团公司/销售板块/销售订单
            string terminalCategoryID = "EBABB15A-AFD8-4072-A5C9-03F1B0B5CDFF";

            var entity      = creatEntity(categoryID);
            var childEntity = creatChildEntity(categoryID);
            //外部实体字段
            OuterEntityField outField = new OuterEntityField()
            {
                Name        = "OutField",
                ID          = Guid.NewGuid().ToString(),
                Description = "外部字段"
            };
            //外部实体
            OuterEntity outEntity = new OuterEntity()
            {
                ID          = Guid.NewGuid().ToString(),
                Name        = "OEntity",
                Description = "外部实体"
            };


            //子表入库
            DEObjectOperations.InstanceWithoutPermissions.AddEntity(childEntity);
            //子表CodeName
            string childCodeName = childEntity.CodeName;
            //主表字段跟子表关联
            var field = entity.Fields[0];

            field.FieldType = FieldTypeEnum.Collection;
            field.ReferenceEntityCodeName = childCodeName;
            // field.OuterEntityFields.Add(outField);
            //主表入库
            DEObjectOperations.InstanceWithoutPermissions.AddEntity(entity);

            //实体字段与外部实体字段的Mapping
            EntityFieldMapping fieldMapping = new EntityFieldMapping()
            {
                FieldID           = field.ID,
                FieldDefaultValue = field.DefaultValue,
                FieldDesc         = field.Description,
                FieldLength       = field.Length,
                FieldName         = field.Name,
                FieldTypeName     = field.FieldType.ToString(),
                //OuterFieldID = outField.ID,
                //OuterFieldName = outField.Name,
                SortNo = field.SortNo
            };
            List <EntityFieldMapping> entityFieldMappingCollection = new List <EntityFieldMapping>();

            entityFieldMappingCollection.Add(fieldMapping);
            //实体和外部实体的Mapping
            EntityMapping mapping = new EntityMapping()
            {
                InnerEntity                  = entity,
                OuterEntityID                = outEntity.ID,
                OuterEntityName              = outEntity.Name,
                OuterEntityInType            = Contract.InType.StandardInterface,
                EntityFieldMappingCollection = entityFieldMappingCollection
            };

            DEObjectOperations.InstanceWithoutPermissions.AddEntityMapping(mapping);

            List <string> entitiesIDs = new List <string>();

            entitiesIDs.Add(entity.ID);
            entitiesIDs.Add(childEntity.ID);
            List <string> categoriesIDs = new List <string>();

            categoriesIDs.Add(terminalCategoryID);
            DEObjectOperations.InstanceWithoutPermissions.CopyEntities(entitiesIDs, categoriesIDs);

            DynamicEntity copyEntity      = DEDynamicEntityAdapter.Instance.LoadByCodeName("/集团公司/销售板块/销售订单/" + entity.Name) as DynamicEntity;
            DynamicEntity copyChildEntity = DEDynamicEntityAdapter.Instance.LoadByCodeName("/集团公司/销售板块/销售订单/" + childEntity.Name) as DynamicEntity;

            Assert.IsNotNull(copyEntity, string.Format("实体[/集团公司/销售板块/销售订单/{0}]复制失败", entity.Name));
            Assert.IsNotNull(copyChildEntity, string.Format("子实体[/集团公司/销售板块/销售订单/{0}]复制失败", childEntity.Name));
            Assert.AreEqual(copyEntity.Fields[0].FieldType, FieldTypeEnum.Collection, string.Format("实体[/集团公司/销售板块/销售订单/{0}]的字段复制失败", entity.Name));
            Assert.AreEqual(copyEntity.Fields[0].ReferenceEntityCodeName, copyChildEntity.CodeName, string.Format("实体[/集团公司/销售板块/销售订单/{0}]的字段复制失败", entity.Name));
            //Assert.AreEqual(copyEntity.OuterEntities.Count, entity.OuterEntities.Count, "实体字段外部实体复制失败");
            //Assert.AreEqual(copyEntity.OuterEntities[0].Name, entity.OuterEntities[0].Name, "实体字段外部实体复制失败");
            //Assert.AreEqual(copyEntity.Fields[0].OuterEntityFields.Count, 1, "实体字段外部实体字段复制失败");
            //Assert.AreEqual(copyEntity.Fields[0].OuterEntityFields.Count, entity.Fields[0].OuterEntityFields.Count, "实体字段外部实体字段复制失败");
            //Assert.AreEqual(copyEntity.Fields[0].OuterEntityFields[0].Name, "OutField", "实体字段外部实体字段复制失败");
        }
Exemplo n.º 47
0
 /// <summary>
 /// Return an object that represents an IDataStream, but is serializable
 /// </summary>
 public Dictionary<string, object> Prepare(DynamicEntity dynamicEntity)
 {
     return Prepare(dynamicEntity.Entity);
 }
Exemplo n.º 48
0
        private static async Task ActivityChanged(ProcessActivityChangedEventArgs args, WorkflowRuntime runtime)
        {
            if (!args.TransitionalProcessWasCompleted)
            {
                return;
            }

            var historyModel = await MetadataToModelConverter.GetEntityModelByModelAsync("DocumentTransitionHistory");

            var emptyHistory = (await historyModel.GetAsync(Filter.And.Equal(Null.Value, "EmployeeId").Equal(args.ProcessId, "DocumentId")
                                                            .Equal(Null.Value, "TransitionTime"))).Select(h => h.GetId()).ToList();
            await historyModel.DeleteAsync(emptyHistory);

            await runtime.PreExecuteFromCurrentActivityAsync(args.ProcessId);

            var nextState     = WorkflowInit.Runtime.GetLocalizedStateName(args.ProcessId, args.ProcessInstance.CurrentState);
            var documentModel = await MetadataToModelConverter.GetEntityModelByModelAsync("Document");

            var document = (await documentModel.GetAsync(Filter.And.Equal(args.ProcessId, "Id"))).FirstOrDefault() as dynamic;

            if (document == null)
            {
                return;
            }

            //document.StateName = nextState;
            document.State = args.ProcessInstance.CurrentState;
            await documentModel.UpdateSingleAsync(document as DynamicEntity);

            var newActors = await Runtime.GetAllActorsForDirectCommandTransitionsAsync(args.ProcessId);

            var newInboxes = new List <dynamic>();

            foreach (var newActor in newActors)
            {
                var newInboxItem = new DynamicEntity() as dynamic;
                newInboxItem.Id         = Guid.NewGuid();
                newInboxItem.IdentityId = newActor;
                newInboxItem.ProcessId  = args.ProcessId;
                newInboxes.Add(newInboxItem);
            }

            var userIdsForNotification = new List <string>();

            userIdsForNotification.AddRange(newInboxes.Select(a => (string)(a as dynamic).IdentityId));

            var inboxModel = await MetadataToModelConverter.GetEntityModelByModelAsync("WorkflowInbox");

            using (var shared = new SharedTransaction())
            {
                await shared.BeginTransactionAsync();

                var existingInbox = (await inboxModel.GetAsync(Filter.And.Equal(args.ProcessId, "ProcessId")));
                userIdsForNotification.AddRange(existingInbox.Select(a => (string)(a as dynamic).IdentityId));
                var existingInboxIds = existingInbox.Select(i => i.GetId()).ToList();
                await inboxModel.DeleteAsync(existingInboxIds);

                await inboxModel.InsertAsync(newInboxes);

                await shared.CommitAsync();
            }

            userIdsForNotification = userIdsForNotification.Distinct().ToList();
            Func <Task> task = async() => { await ClientNotifiers.NotifyClientsAboutInboxStatus(userIdsForNotification); };

            task.FireAndForgetWithDefaultExceptionLogger();
        }
    public void GetNameWorks()
    {
        dynamic currency = new DynamicEntity("Currency");

        Assert.Equal("Currency", currency.Name);
    }
Exemplo n.º 50
0
        protected bool addProperties(string entityName)
        {
            try
            {
                m_dynamicEntity_ = new DynamicEntity(entityName);

                foreach (object param in m_propertyList)
                {

                    m_workingparam = param.ToString();
                    m_dynamicEntity_.Properties.Add((Property)param);

                }

            }
            catch (Exception ex)
            {
                throw new ESC_CRM_EX.addPropertyException(ex.Message, m_workingparam);
            }
            return true;
        }
Exemplo n.º 51
0
    /// <summary>
    /// Returns the default string value
    /// </summary>
    /// <param name="crmEntity">Entity</param>
    /// <param name="propertyName">Attribute Name</param>
    /// <returns>Attribute value(String)</returns>
    public static string GetDefaultFieldValue(this DynamicEntity crmEntity, string propertyName)
    {
        if (crmEntity.Properties.Contains(propertyName))
        {
            string ret  = string.Empty;
            string type = null;


            try
            {
                //TODO: Google "CrmTypes"
                type = crmEntity.Properties[propertyName].GetType().ToString();
            }
            catch (Exception exception)
            {
                type = exception.Message;
                ret  = exception.Message;
                return(null);
            }

            if (type == "Microsoft.Crm.Sdk.Owner")
            {
                Owner owner = (Owner)crmEntity[propertyName];
                return(owner.name);
            }
            if (type == "Microsoft.Crm.Sdk.Customer")
            {
                Customer customer = (Customer)crmEntity[propertyName];
                return(customer.name);
            }
            if (type == "Microsoft.Crm.Sdk.CrmDateTime")
            {
                CrmDateTimeProperty crmDataTime = new CrmDateTimeProperty(propertyName, (CrmDateTime)crmEntity.Properties[propertyName]);
                return(crmDataTime.Value.date);
            }
            if (type == "Microsoft.Crm.Sdk.CrmBoolean")
            {
                CrmBooleanProperty crmBooleanProperty = new CrmBooleanProperty(propertyName, (CrmBoolean)crmEntity.Properties[propertyName]);
                ret = crmBooleanProperty.Value.Value.ToString();
                return(ret);
            }
            if (type == "System.String")
            {
                return(crmEntity.Properties[propertyName].ToString());
            }
            if (type == "Microsoft.Crm.Sdk.Lookup")
            {
                Lookup crmLookup = (Lookup)crmEntity[propertyName];
                return(crmLookup.name);
            }
            if (type == "Microsoft.Crm.Sdk.Picklist")
            {
                Picklist crmPicklist = (Picklist)crmEntity[propertyName];
                return(crmPicklist.name);
            }
            if (type == "Microsoft.Crm.Sdk.CrmNumber")
            {
                CrmNumber num = (CrmNumber)crmEntity[propertyName];
                return(num.Value.ToString());
            }
            return(ret);
        }
        else
        {
            return("The Entity doesn't have this property defined");
        }
    }
 public DictionaryPropertyGridAdapter(DynamicEntity d)
 {
     _dynamic = d;
 }
Exemplo n.º 53
0
    //Field Value Object
    /// <summary>
    /// Returns the entity attribute
    /// </summary>
    /// <param name="dynamicEntityInstance">Entity</param>
    /// <param name="entityPropertyLogicalName">Attribute name<</param>
    /// <returns>Attribute value(Object)</returns>
    public static Object GetPropertyObj(this DynamicEntity dynamicEntityInstance, string entityPropertyLogicalName)
    {
        if (dynamicEntityInstance.Properties.Contains(entityPropertyLogicalName))
        {
            string propertyType = null;
            Object returnObject;
            try
            {
                //"CrmTypes"
                propertyType = dynamicEntityInstance.Properties[entityPropertyLogicalName].GetType().ToString();
            }
            catch (Exception e)
            {
                propertyType = e.Message;
                returnObject = e.Message;
                return(null);
            }

            if (propertyType == "Microsoft.Crm.Sdk.Owner")
            {
                Owner ownerObject = (dynamicEntityInstance[entityPropertyLogicalName]) as Owner;
                returnObject = new { Value = ownerObject, Type = propertyType };
                return(returnObject);
            }
            if (propertyType == "Microsoft.Crm.Sdk.Customer")
            {
                Customer customerObject = (dynamicEntityInstance[entityPropertyLogicalName]) as Customer;
                returnObject = new { Value = customerObject, Type = propertyType };
                return(returnObject);
            }
            if (propertyType == "Microsoft.Crm.Sdk.CrmDateTime")
            {
                CrmDateTimeProperty datetimeObject = new CrmDateTimeProperty(entityPropertyLogicalName, (CrmDateTime)dynamicEntityInstance.Properties[entityPropertyLogicalName]);
                returnObject = new { Value = datetimeObject, Type = propertyType };
                return(returnObject);
            }
            if (propertyType == "Microsoft.Crm.Sdk.CrmBoolean")
            {
                CrmBooleanProperty booleanObject = new CrmBooleanProperty(entityPropertyLogicalName, (CrmBoolean)dynamicEntityInstance.Properties[entityPropertyLogicalName]);
                returnObject = new { Value = booleanObject, Type = propertyType };
                return(returnObject);
            }
            if (propertyType == "System.String")
            {
                returnObject = new { Value = (dynamicEntityInstance.Properties[entityPropertyLogicalName]), Type = propertyType };
                return(returnObject);
            }
            if (propertyType == "Microsoft.Crm.Sdk.Lookup")
            {
                Lookup lookupObject = dynamicEntityInstance[entityPropertyLogicalName] as Lookup;
                returnObject = new { Value = lookupObject, Type = propertyType };
                return(returnObject);
            }
            if (propertyType == "Microsoft.Crm.Sdk.Picklist")
            {
                Picklist piclkistObject = dynamicEntityInstance[entityPropertyLogicalName] as Picklist;
                returnObject = new { Value = piclkistObject, Type = propertyType };
                return(returnObject);
            }
        }
        else
        {
            object nullObject = new { value = "Null", type = "Null" };
            return(nullObject);
        }
        object nullreturn = new { value = "null", type = "null" };

        return(nullreturn);
    }
Exemplo n.º 54
0
 public override bool UseBlock(int x, int y, BaseDimension dimension, DynamicEntity entity) => true;
Exemplo n.º 55
0
        private void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                var entity = this.cmbDynamicEntities.SelectedItem as DynamicEntityInfo;
                if (entity != null)
                {
                    if (!entity.Registered) throw new Exception("The Entity hasn't been Registered!");
                    var dynamic = new DynamicEntity(entity);
                    var list = this.dgvDynamicEntities.DataSource as BindingList<DynamicEntity>;
                    if (list == null)
                    {
                        list = new BindingList<DynamicEntity>();
                        this.dgvDynamicEntities.DataSource = list;
                    }
                    list.Add(dynamic);
                    this._unsaved_items.Add(dynamic);
                    this.pnlModified.Visible = true;

                    this.pgrItemEditor.SelectedObject = new DictionaryPropertyGridAdapter((DynamicEntity)dynamic);
                }
            }
            catch (Exception ex)
            {
                OpenNETCF.ORM.MainDemo.Logger.LogException(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
            }
        }
Exemplo n.º 56
0
 public object LookUp(DynamicEntity de, string propName)
 {
     return(GetProperty(de, propName));
 }
Exemplo n.º 57
0
        /// <summary>
        /// This method connects to the CRM server (This is the first method you need to use)
        /// It creates a lead "test" and deletes it to check the connection with CRM.
        /// </summary>
        public bool connect()
        {
            try
            {
                Microsoft.Crm.Sdk.CrmAuthenticationToken token = new Microsoft.Crm.Sdk.CrmAuthenticationToken();
                token.AuthenticationType = 0; // Use Active Directory authentication.
                token.OrganizationName = m_crmName;
                m_crmService.Credentials = new NetworkCredential(m_crmLogin, m_crmPassword, m_crmDomain);
                m_crmService.Url = m_crmURL;
                m_crmService.CrmAuthenticationTokenValue = token;
                m_crmService.PreAuthenticate = true;

                DynamicEntity new_lead = new DynamicEntity("lead");
                StringProperty sp_lead_topic = new StringProperty("subject", "test");
                StringProperty sp_lead_lastname = new StringProperty("lastname", "test");
                new_lead.Properties.Add(sp_lead_lastname);
                new_lead.Properties.Add(sp_lead_topic);

                Guid created_lead = m_crmService.Create(new_lead);

                m_crmService.Delete("lead", created_lead);

                m_isconnected = true;
                return true;
            }
            catch (WebException)
            {
                throw new Exception("Failed to connect to the CRM Server !<br />" +
                    "Please check that the credentials(Login,Password and Domain) provided are correct.<br />" +
                    "<b><u>Addresses</u></b><br /><br />" +
                    "SERVER \t=><a href=\"" + m_crmURL + "\">" + m_crmURL + "</a><br />" +
                    "MD\t =><a href=\"" + m_crmURL_MD + "\">" + m_crmURL_MD + "</a><br />");
            }
            catch (SoapException ex)
            {
                throw new InvalidPluginExecutionException(ex.Detail.SelectSingleNode("//description").InnerText);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 58
0
        public DynamicEntity rowFinder(string[] row, string[] fields, List <int> selectIndex, SimpleCondition condition)
        {
            string[]      returnRow      = row;
            DynamicEntity dynReturn      = null;
            int           conditionIndex = Array.IndexOf(fields, condition.colName);
            string        whereClause    = condition.value;

            switch (condition.opera)
            {
            case "=":
            {
                if (whereClause.Equals(returnRow[conditionIndex]))
                {
                    dynReturn = conditionMatchRows(selectIndex, fields, returnRow);
                }
            }
            break;

            case "!=":
            {
                if (!whereClause.Equals(returnRow[conditionIndex]))
                {
                    dynReturn = conditionMatchRows(selectIndex, fields, returnRow);
                }
            }
            break;

            case "<":
            {
                if (int.TryParse(returnRow[conditionIndex], out int K) &&
                    int.TryParse(whereClause, out int J) &&
                    K < J)
                {
                    dynReturn = conditionMatchRows(selectIndex, fields, returnRow);
                }
            }
            break;

            case ">":
            {
                if (int.TryParse(returnRow[conditionIndex], out int K) &&
                    int.TryParse(whereClause, out int J) &&
                    K > J)
                {
                    dynReturn = conditionMatchRows(selectIndex, fields, returnRow);
                }
            }
            break;

            case ">=":
            {
                if (int.TryParse(returnRow[conditionIndex], out int K) &&
                    int.TryParse(whereClause, out int J) &&
                    K >= J)
                {
                    dynReturn = conditionMatchRows(selectIndex, fields, returnRow);
                }
            }
            break;

            case "<=":
            {
                if (int.TryParse(returnRow[conditionIndex], out int K) &&
                    int.TryParse(whereClause, out int J) &&
                    K <= J)
                {
                    dynReturn = conditionMatchRows(selectIndex, fields, returnRow);
                }
            }
            break;
            }
            return(dynReturn);
        }
Exemplo n.º 59
0
        protected bool createPartyListProperties(ArrayList partyListParams)
        {
            //loop to create the Boolean properties

            try
            {
                ArrayList paramtab = (ArrayList)partyListParams;
                createm_workingparam(paramtab[1], paramtab[2], paramtab[3]);
                DynamicEntity activityParty = new DynamicEntity("activityparty");
                LookupProperty partyProperty = new LookupProperty("partyid", new Lookup(paramtab[2].ToString(), new Guid(paramtab[3].ToString())));
                activityParty.Properties.Add(partyProperty);
                DynamicEntityArrayProperty customersProperty = new DynamicEntityArrayProperty(paramtab[1].ToString(), new DynamicEntity[] { activityParty });
                m_propertyList.Add(customersProperty);
            }
            catch (Exception ex)
            {
                throw new ESC_CRM_EX.createPropertyException(ex.Message, " partylist" + m_workingparam);
            }

            return true;
        }
Exemplo n.º 60
0
        public static void SyncData()
        {
            DataTable dt;
            //## Barcode ##//
            try
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                dt = Util.DBQuery("SELECT * FROM Barcode WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("BarcodeStock");
                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["Barcode"].ToString());
                    d.OrderNo = row["OrderNo"].ToString();
                    d.Product = row["Product"].ToString();
                    //d.Cost = double.Parse(row["Cost"].ToString());
                    if (row["Cost"].ToString() == "" || row["Cost"].ToString() == null) { d.Cost = 0; } else { d.Cost = double.Parse(row["Cost"].ToString()); }
                    if (row["OperationCost"].ToString() == "" || row["OperationCost"].ToString() == null) { d.OperationCost = 0; } else { d.OperationCost = double.Parse(row["OperationCost"].ToString()); }
                    //d.OperationCost = double.Parse(row["OperationCost"].ToString());
                    d.SellPrice = double.Parse(row["SellPrice"].ToString());
                    d.ReceivedDate = Convert.ToDateTime(row["ReceivedDate"].ToString());
                    d.ReceivedBy = row["ReceivedBy"].ToString();
                    d.SellNo = row["SellNo"].ToString();
                    if (row["SellDate"].ToString() == "")
                    {
                        d.SellDate = "";
                    }
                    else
                    {
                        d.SellDate = Convert.ToDateTime(row["SellDate"].ToString());
                    }
                    d.SellBy = row["SellBy"].ToString();
                    d.SellFinished = row["SellFinished"].ToString() == "True" ? true : false;
                    d.Customer = row["Customer"].ToString();
                    if (row["Stock"].ToString() == "" || row["Stock"].ToString() == null) { d.Stock = 0; } else { d.Stock = row["Stock"].ToString(); }
                    if (row["Comment"].ToString() == "" || row["Comment"].ToString() == null) { d.Comment = ""; } else { d.Comment = row["Comment"].ToString(); }
                    if (row["Ship"].ToString() == "" || row["Ship"].ToString() == null) { d.Ship = 0; } else { d.Ship = row["Ship"].ToString(); }
                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE Barcode SET Sync = 0 WHERE Barcode = {0}", row["Barcode"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
                //    if (row["ReceivedDate"].ToString() == "" && row["SellDate"].ToString() == "")
                //        batchOperation.InsertOrMerge(Util.RenderBarcodeNoDateData(row));
                //    else if (row["SellDate"].ToString() == "")
                //        batchOperation.InsertOrMerge(Util.RenderBarcodeNoSellDateData(row));
                //    else if (row["ReceivedDate"].ToString() == "")
                //        batchOperation.InsertOrMerge(Util.RenderBarcodeNoReceivedDateData(row));
                //    else
                //        batchOperation.InsertOrMerge(Util.RenderBarcodeData(row));

                //    Util.DBExecute(string.Format("UPDATE Barcode SET Sync = 0 WHERE Barcode = {0}", row["Barcode"].ToString()));

                //    if (batchOperation.Count == 100)
                //    {
                //        azureTable.ExecuteBatch(batchOperation);
                //        batchOperation = new TableBatchOperation();
                //    }
                //}
                //if (batchOperation.Count > 0)
                //    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## Product ##//
            try
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                dt = Util.DBQuery("SELECT * FROM Product WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("Product");
                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["ID"].ToString());
                    d.Brand = row["Brand"].ToString();
                    d.Category = row["Category"].ToString();
                    d.Name = row["Name"].ToString();
                    d.CoverImage = row["CoverImage"].ToString();
                    if (row["Warranty"].ToString() == "" || row["Warranty"].ToString() == null) { d.Warranty = 0; } else { d.Warranty = int.Parse(row["Warranty"].ToString()); }
                    if (row["Price"].ToString() == "" || row["Price"].ToString() == null) { d.Price = 0; } else { d.Price = double.Parse(row["Price"].ToString()); }
                    if (row["Price1"].ToString() == "" || row["Price1"].ToString() == null) { d.Price1 = 0; } else { d.Price1 = double.Parse(row["Price1"].ToString()); }
                    if (row["Price2"].ToString() == "" || row["Price2"].ToString() == null) { d.Price2 = 0; } else { d.Price2 = double.Parse(row["Price2"].ToString()); }
                    if (row["Price3"].ToString() == "" || row["Price3"].ToString() == null) { d.Price3 = 0; } else { d.Price3 = double.Parse(row["Price3"].ToString()); }
                    if (row["Price4"].ToString() == "" || row["Price4"].ToString() == null) { d.Price4 = 0; } else { d.Price4 = double.Parse(row["Price4"].ToString()); }
                    if (row["Price5"].ToString() == "" || row["Price5"].ToString() == null) { d.Price5 = 0; } else { d.Price5 = double.Parse(row["Price5"].ToString()); }
                    if (row["Cost"].ToString() == "" || row["Cost"].ToString() == null) { d.Cost = 0; } else { d.Cost = double.Parse(row["Cost"].ToString()); }
                    if (row["Quantity"].ToString() == "" || row["Quantity"].ToString() == null) { d.Quantity = 0; } else { d.Quantity = double.Parse(row["Quantity"].ToString()); }

                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE Product SET Sync = '0' WHERE ID = '{0}' AND Shop = '{1}'", row["ID"].ToString(),Param.ShopId));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## CategoryProfit ##//
            try
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                dt = Util.DBQuery("SELECT * FROM CategoryProfit WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("CategoryProfit");
                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["ID"].ToString());
                    if (row["Price"].ToString() == "" || row["Price"].ToString() == null) { d.Price = 0; } else { d.Price = double.Parse(row["Price"].ToString()); }
                    if (row["Price1"].ToString() == "" || row["Price1"].ToString() == null) { d.Price1 = 0; } else { d.Price1 = double.Parse(row["Price1"].ToString()); }
                    if (row["Price2"].ToString() == "" || row["Price2"].ToString() == null) { d.Price2 = 0; } else { d.Price2 = double.Parse(row["Price2"].ToString()); }
                    if (row["Price3"].ToString() == "" || row["Price3"].ToString() == null) { d.Price3 = 0; } else { d.Price3 = double.Parse(row["Price3"].ToString()); }
                    if (row["Price4"].ToString() == "" || row["Price4"].ToString() == null) { d.Price4 = 0; } else { d.Price4 = double.Parse(row["Price4"].ToString()); }
                    if (row["Price5"].ToString() == "" || row["Price5"].ToString() == null) { d.Price5 = 0; } else { d.Price5 = double.Parse(row["Price5"].ToString()); }
                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE CategoryProfit SET Sync = 0 WHERE ID = {0}", row["ID"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## Customer ##//
            try
            {
                dt = Util.DBQuery("SELECT * FROM Customer WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("Customer");
                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["ID"].ToString());
                    //CustomerEntity d = new CustomerEntity(Param.ShopId, row["ID"].ToString());
                    d.Member = row["Member"].ToString();
                    d.Name = row["Firstname"].ToString() + " " + row["Lastname"].ToString();
                    d.Firstname = row["Firstname"].ToString();
                    d.Lastname = row["Lastname"].ToString();
                    d.Nickname = row["Nickname"].ToString();
                    d.CitizenID = row["CitizenID"].ToString();
                    try { d.Birthday = Convert.ToDateTime(row["Birthday"].ToString()); } catch { }
                    d.Sex = row["Sex"].ToString();
                    d.CardNo = row["CardNo"].ToString();
                    d.Mobile = row["Mobile"].ToString();
                    d.Email = row["Email"].ToString();
                    d.ShopName = row["ShopName"].ToString();
                    d.Address = row["Address"].ToString();
                    d.Address2 = row["Address2"].ToString();
                    d.SubDistrict = row["SubDistrict"].ToString();
                    d.District = row["District"].ToString();
                    d.Province = row["Province"].ToString();
                    d.ZipCode = row["ZipCode"].ToString();
                    d.ShopSameAddress = row["ShopSameAddress"].ToString() == "True";
                    d.ShopAddress = row["ShopAddress"].ToString();
                    d.ShopAddress2 = row["ShopAddress2"].ToString();
                    d.ShopSubDistrict = row["ShopSubDistrict"].ToString();
                    d.ShopDistrict = row["ShopDistrict"].ToString();
                    d.ShopProvince = row["ShopProvince"].ToString();
                    d.ShopZipCode = row["ShopZipCode"].ToString();
                    d.SellPrice = int.Parse(row["SellPrice"].ToString());
                    d.DiscountPercent = int.Parse(row["DiscountPercent"].ToString());
                    d.Credit = int.Parse(row["Credit"].ToString());
                    d.Comment = row["Comment"].ToString();
                    try { d.AddDate = Convert.ToDateTime(row["AddDate"].ToString()); } catch { }
                    d.AddBy = row["AddBy"].ToString();
                    try { d.UpdateDate = Convert.ToDateTime(row["UpdateDate"].ToString()); } catch { }
                    d.UpdateBy = row["UpdateBy"].ToString();

                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE Customer SET Sync = 0 WHERE ID = '{0}'", row["ID"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## SellHeader ##//
            try
            {
                dt = Util.DBQuery("SELECT * FROM SellHeader WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("SellHeader");
                azureTable.CreateIfNotExists();

                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["SellNo"].ToString());
                    //SellHeaderEntity d = new SellHeaderEntity(Param.ShopId, row["SellNo"].ToString());
                    d.Customer = row["Customer"].ToString();
                    d.CustomerSex = row["CustomerSex"].ToString();
                    d.CustomerAge = int.Parse(row["CustomerAge"].ToString());
                    d.Credit = int.Parse(row["Credit"].ToString());
                    d.PayType = row["PayType"].ToString();
                    d.Cash = double.Parse(row["Cash"].ToString());
                    d.DiscountPercent = double.Parse(row["DiscountPercent"].ToString());
                    d.DiscountCash = double.Parse(row["DiscountCash"].ToString());
                    d.Paid = row["Paid"].ToString() == "True";

                    if ((row["TotalPrice"].ToString() == "") || (row["TotalPrice"].ToString() == "0"))
                    {
                        d.Profit = 0;
                    }
                    else
                    {
                        d.Profit = double.Parse(row["Profit"].ToString());
                    }

                    if ((row["TotalPrice"].ToString() == "") || (row["TotalPrice"].ToString() == "0"))
                    {
                        d.TotalPrice = 0;
                    }
                    else
                    {
                        d.TotalPrice = double.Parse(row["TotalPrice"].ToString());
                    }

                    d.PointReceived = int.Parse(row["PointReceived"].ToString());
                    d.PointUse = int.Parse(row["PointUse"].ToString());
                    d.Comment = row["Comment"].ToString();
                    d.SellDate = Convert.ToDateTime(row["SellDate"].ToString());
                    d.SellBy = row["SellBy"].ToString();
                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE SellHeader SET Sync = 0 WHERE SellNo = '{0}'", row["SellNo"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## SellDetail ##//
            try
            {
                dt = Util.DBQuery("SELECT * FROM SellDetail WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("SellDetail");
                azureTable.CreateIfNotExists();

                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["SellNo"].ToString() + "-" + row["Product"].ToString());

                    if ((row["SellPrice"].ToString() == "") || (row["SellPrice"].ToString() == "0"))
                    {
                        d.SellPrice = 0;
                    }
                    else
                    {
                        d.SellPrice = double.Parse(row["SellPrice"].ToString());
                    }

                    if ((row["Cost"].ToString() == "") || (row["Cost"].ToString() == "0"))
                    {
                        d.Cost = 0;
                    }
                    else
                    {
                        d.Cost = double.Parse(row["Cost"].ToString());
                    }

                    if ((row["Quantity"].ToString() == "") || (row["Quantity"].ToString() == "0"))
                    {
                        d.Quantity = 0;
                    }
                    else
                    {
                        d.Quantity = int.Parse(row["Quantity"].ToString());
                    }
                    d.Comment = row["Comment"].ToString();
                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE SellDetail SET Sync = 0 WHERE SellNo = '{0}' AND Product = '{1}'",
                        row["SellNo"].ToString(), row["Product"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## PurchaseOrder ##//
            try
            {
                dt = Util.DBQuery("SELECT * FROM PurchaseOrder WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("PurchaseOrder");
                azureTable.CreateIfNotExists();

                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["OrderNo"].ToString() + "-" + row["Product"].ToString());
                    d.ReceivedDate = Convert.ToDateTime(row["ReceivedDate"].ToString());
                    if ((row["ReceivedQty"].ToString() == "") || (row["ReceivedQty"].ToString() == "0"))
                    {
                        d.ReceivedQty = 0;
                    }
                    else
                    {
                        d.ReceivedQty = double.Parse(row["ReceivedQty"].ToString());
                    }
                    d.ReceivedBy = row["ReceivedBy"].ToString();
                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE PurchaseOrder SET Sync = 0 WHERE OrderNo = '{0}' AND Product = '{1}'",
                        row["OrderNo"].ToString(), row["Product"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## Return ##//
            try
            {
                dt = Util.DBQuery("SELECT * FROM ReturnProduct WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("ReturnProduct");
                azureTable.CreateIfNotExists();

                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["SellNo"].ToString() + "-" + row["Barcode"].ToString());
                    d.SellPrice = double.Parse(row["SellPrice"].ToString());
                    d.ReturnDate = Convert.ToDateTime(row["ReturnDate"].ToString());
                    d.Product = row["Product"].ToString();
                    d.ReturnBy = row["ReturnBy"].ToString();
                    d.Quantity = int.Parse(row["Quantity"].ToString());
                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE ReturnProduct SET Sync = 0 WHERE SellNo = '{0}' AND Barcode = '{1}'", row["SellNo"].ToString(), row["Barcode"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }

            //## Claim ##//
            try
            {
                dt = Util.DBQuery("SELECT * FROM Claim WHERE Sync = 1");

                var azureTable = Param.AzureTableClient.GetTableReference("Claim");
                azureTable.CreateIfNotExists();

                TableBatchOperation batchOperation = new TableBatchOperation();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    dynamic d = new DynamicEntity(Param.ShopId, row["ClaimNo"].ToString());
                    d.Barcode = row["Barcode"].ToString();
                    d.ClaimType = row["ClaimType"].ToString();
                    d.BarcodeClaim = row["BarcodeClaim"].ToString();
                    d.Description = row["Description"].ToString();
                    d.Firstname = row["Firstname"].ToString();
                    d.Lastname = row["Lastname"].ToString();
                    d.Nickname = row["Nickname"].ToString();
                    d.Tel = row["Tel"].ToString();
                    d.Email = row["Email"].ToString();
                    d.Price = double.Parse(row["Price"].ToString());
                    if (row["PriceClaim"].ToString() == "" || row["PriceClaim"].ToString() == null) { d.PriceClaim = 0; } else { d.PriceClaim = double.Parse(row["PriceClaim"].ToString()); }
                    d.ClaimDate = Convert.ToDateTime(row["ClaimDate"].ToString());
                    d.Product = row["Product"].ToString();
                    d.ClaimBy = row["ClaimBy"].ToString();
                    batchOperation.InsertOrMerge(d);

                    Util.DBExecute(string.Format("UPDATE Claim SET Sync = 0 WHERE ClaimNo = '{0}' AND Barcode = '{1}'", row["ClaimNo"].ToString(), row["Barcode"].ToString()));

                    if (batchOperation.Count == 100)
                    {
                        azureTable.ExecuteBatch(batchOperation);
                        batchOperation = new TableBatchOperation();
                    }
                }
                if (batchOperation.Count > 0)
                    azureTable.ExecuteBatch(batchOperation);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex.Message);
                WriteErrorLog(ex.StackTrace);
            }
        }