Ejemplo n.º 1
0
        public static string BuildContent(Tag tag)
        {
            var settings = CMS.CMS.EntitySettings;
            var helper = new EntityHelper<Event>(settings);
            var result = helper.Details(tag.Id);
            var model = EntityViewHelper.BuildViewModelForDetails(result, "Event", "details", settings);

            return "";

        }
Ejemplo n.º 2
0
        public void Insert_Index3()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM TestUnique.E;",
                        "DELETE FROM TestUnique.R;"
                    });

                var repository = container.Resolve<Common.DomRepository>();
                var helper = new EntityHelper(container);

                var r1 = new TestUnique.R { S = "r1" };
                var r2 = new TestUnique.R { S = "r2" };
                repository.TestUnique.R.Insert(new[] { r1, r2 });

                helper.Insert("a", 1, r1);
                helper.Insert("b", 1, r1);
                helper.Insert("a", 2, r1);
                helper.Insert("a", 1, r2);
                helper.InsertShouldFail("a", 1, r1);
            }
        }
Ejemplo n.º 3
0
        public void Insert_Index3()
        {
            using (var executionContext = new CommonTestExecutionContext())
            {
                executionContext.SqlExecuter.ExecuteSql(new[]
                    {
                        "DELETE FROM TestUnique.E;",
                        "DELETE FROM TestUnique.R;"
                    });

                var repository = new Common.DomRepository(executionContext);
                var helper = new EntityHelper(executionContext, repository);

                var r1 = new TestUnique.R { S = "r1" };
                var r2 = new TestUnique.R { S = "r2" };
                repository.TestUnique.R.Insert(new[] { r1, r2 });

                helper.Insert("a", 1, r1);
                helper.Insert("b", 1, r1);
                helper.Insert("a", 2, r1);
                helper.Insert("a", 1, r2);
                helper.InsertShouldFail("a", 1, r1);
            }
        }
Ejemplo n.º 4
0
 public void CanGetTableName()
 {
     Assert.IsTrue(EntityHelper.GetTableName(typeof(Eod)) == "Eod");
     Assert.IsTrue(EntityHelper.GetTableName(typeof(Company)) == "Company");
 }
Ejemplo n.º 5
0
        public blog_tb_blog GetEntity(string id)
        {
            EntityHelper <blog_tb_blog> eq = new EntityHelper <blog_tb_blog>("blog_tb_blog", "blogID", null);

            return(eq.GetEntity(id, DbInstance));
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Determines whether given entity name is defiend in the early bound assembly
 /// </summary>
 /// <param name="entityLogicalName">Name of the entity logical.</param>
 /// <returns></returns>
 public bool IsTypeDefined(string entityLogicalName)
 {
     return(EntityHelper.IsTypeDefined(EarlyBoundEntityAssembly, EarlyBoundNamespace, entityLogicalName));
 }
Ejemplo n.º 7
0
        private void ProcessItem(IMySlimBlock target)
        {
            if (Sync.IsServer)
            {
                if (!IsEnabled())
                {
                    Logging.Instance.WriteLine("CANCELLING Deconstruction Target due to being disabled");
                    CancelTarget(target);
                    return;
                }

                if (!NaniteConstructionPower.HasRequiredPowerForCurrentTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock))
                {
                    Logging.Instance.WriteLine("CANCELLING Deconstruction Target due to power shortage");
                    CancelTarget(target);
                    return;
                }

                if (m_constructionBlock.FactoryState != NaniteConstructionBlock.FactoryStates.Active)
                {
                    return;
                }

                NaniteGrinder grinder = (NaniteGrinder)m_constructionBlock.ToolManager.Tools.FirstOrDefault(x => x.TargetBlock == target && x is NaniteGrinder);
                if (grinder == null)
                {
                    double distance = EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, target);
                    int    time     = (int)Math.Max(GetMinTravelTime() * 1000f, (distance / GetSpeed()) * 1000f);
                    grinder = new NaniteGrinder(m_constructionBlock, target, (int)(time / 2.5f), NaniteConstructionManager.Settings.DeconstructionPerformanceFriendly);
                    m_constructionBlock.ToolManager.Tools.Add(grinder);
                    m_constructionBlock.SendAddTarget(target, TargetTypes.Deconstruction);
                }

                if (m_areaTargetBlocks.ContainsKey(target.CubeGrid))
                {
                    if (!m_areaTargetBlocks[target.CubeGrid].IsInsideBox(target.CubeGrid.WorldAABB, false))
                    {
                        CancelTarget(target);
                        RemoveGridTarget(target.CubeGrid);
                        return;
                    }

                    if (target.CubeGrid.Physics.LinearVelocity.LengthSquared() != 0f || target.CubeGrid.Physics.AngularVelocity.LengthSquared() != 0f)
                    {
                        CancelTarget(target);
                        return;
                    }
                }

                if (target.IsDestroyed || target.IsFullyDismounted || target.CubeGrid.GetCubeBlock(target.Position) == null || (target.FatBlock != null && target.FatBlock.Closed))
                {
                    CompleteTarget(target);
                    return;
                }

                if (target.CubeGrid.Closed)
                {
                    Logging.Instance.WriteLine("CANCELLING Deconstruction Target due to grid being closed");
                    CancelTarget(target);
                    return;
                }

                if (EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, target) > m_maxDistance)
                {
                    Logging.Instance.WriteLine("CANCELLING Deconstruction Target due to target being out of range");
                    CancelTarget(target);
                    return;
                }
            }

            CreateDeconstructionParticle(target);
        }
Ejemplo n.º 8
0
        public void TestUserSession()
        {
            // What is being tested
            // 1. Changed values in user session are immediately saved in the database and session version is incremented
            // 2. LastUsedOn is being updated (on background thread, with 10 seconds increments)
            // 3. Session version higher than current cached causes session refresh
            var client      = Startup.Client;
            var timeService = Startup.BooksApp.TimeService;
            //Login as Dora
            var doraLogin     = LoginAs("dora");
            var authToken     = doraLogin.AuthenticationToken;
            var serverSession = Startup.BooksApp.OpenSystemSession();
            var sessionRec    = serverSession.EntitySet <IUserSession>().Where(s => s.WebSessionToken == authToken).FirstOrDefault();

            Assert.IsNotNull(sessionRec, "Session record not found.");
            var oldVersion = sessionRec.Version;

            client.ExecutePost <object, HttpStatusCode>(null, "/api/special/sessionvalue?name=varName&value=varValue1");
            //Read session rec
            EntityHelper.RefreshEntity(sessionRec);
            var serValues = sessionRec.Values;

            Assert.IsTrue(serValues.Contains("varName"), "Expected serialized values to contain 'varName'.");
            Assert.IsTrue(serValues.Contains("varValue1"), "Expected serialized values to contain 'varValue1'.");
            var newVersion  = sessionRec.Version;
            var oldLastUsed = sessionRec.LastUsedOn;

            Assert.IsTrue(newVersion > oldVersion, "Expected version increment.");
            //Force updating lastUsedOn value: fast forward time one minute, make a call
            timeService.SetCurrentOffset(TimeSpan.FromMinutes(1));
            //var varValue = client.ExecuteGet<string>("/api/special/sessionvalue?name=varName");
            var varValue = client.ExecuteGet <string>("/api/special/sessionvalue?name=varName");

            Assert.AreEqual("varValue1", varValue, "Expected 'varValue1' as a value.");
            // The last API call came a minute later after the first one (according to time service);
            // The userSesson.LastUsedOn value is updated with 10 seconds increments, so it should be updated in memory
            // and scheduled with background service to update in the database. BackgroundSave service runs every 1 second.
            // Wait for 2 seconds to let db update execute, and check the value.
            Thread.Sleep(2000);
            EntityHelper.RefreshEntity(sessionRec);
            var newLastUsed = sessionRec.LastUsedOn;

            Assert.IsTrue(oldLastUsed.AddSeconds(50) < newLastUsed, "Expected new last used to be a minute away.");
            //set time back
            Startup.BooksApp.TimeService.SetCurrentOffset(TimeSpan.FromMilliseconds(0)); //restore time

            // Test that cached user session is refreshed if incoming session version is higher.
            // Scenario: we pretend that call goes through another web server and changes foo value in the session;
            // UserSession in the database is updated, session version is incremented and new version is returned in
            // X-Versions header. If we make a new call with this new version value in the header, and it goes to another
            // web server in a farm with stale cache of user session, then web server should recognize from higher version
            // that cache is stale, and it would reload session from the database.
            // We simulate this scenario by changing value directly in the database (pretending it's done thru other web server)
            //Change foo value in the database - pretend a call thru another web server updated it.
            // Then we hand-craft a version token with incremented session version (we pretend the call thru another server
            // returned this incremented value). If we make a call with this higher version value, the server should detect
            // that user session in cache is stale and it needs to be refreshed. It will refresh it and will return a new
            // fooValue.
            // First let's get the old value, and get the version token
            string incomingVersionToken = null;
            var    xVersions            = "X-Versions";

            client.Settings.ResponseSpy = r => { incomingVersionToken = r.GetHeaderValue(xVersions); }; //setup spy
            varValue = client.ExecuteGet <string>("/api/special/sessionvalue?name=varname");
            client.Settings.ResponseSpy = null;
            Assert.AreEqual("varValue1", varValue, "Expected 'varValue1' as a value.");
            var versionArr = incomingVersionToken.Split(',').Select(s => int.Parse(s)).ToArray();

            //Change value directly in the database by replacing it in XML (serialized value set)
            sessionRec.Values = serValues.Replace("varValue1", "varValue2");
            serverSession.SaveChanges();
            // After update, the current session version should be incremented, and returned with version token
            // Pretend we have new versions token
            versionArr[0] = versionArr[0] + 1;
            var newVersionToken = string.Join(",", versionArr);

            client.AddRequestHeader(xVersions, newVersionToken);
            varValue = client.ExecuteGet <string>("/api/special/sessionvalue?name=varname");
            Assert.AreEqual("varValue2", varValue, "Expected 'varValue2' as a value.");
            client.RemoveRequestHeader(xVersions);

            //clean up
            // delete all web call entries made when time was one-minute forward; otherwise, other tests will fail
            // (some tests get 'latest' web call and check it, so these future entries would break them)
            var delQuery = serverSession.EntitySet <IWebCallLog>().Where(wc => wc.CreatedOn > timeService.UtcNow);

            delQuery.ExecuteDelete <IWebCallLog>();
        }
Ejemplo n.º 9
0
        public override void FindTargets(ref Dictionary <string, int> available)
        {
            ComponentsRequired.Clear();

            if (!IsEnabled())
            {
                return;
            }

            if (TargetList.Count >= GetMaximumTargets())
            {
                if (PotentialTargetList.Count > 0)
                {
                    m_lastInvalidTargetReason = "Maximum targets reached.  Add more upgrades!";
                }

                return;
            }

            NaniteConstructionInventory inventoryManager = m_constructionBlock.InventoryManager;
            Vector3D sourcePosition          = m_constructionBlock.ConstructionBlock.GetPosition();
            Dictionary <string, int> missing = new Dictionary <string, int>();

            using (m_lock.AcquireExclusiveUsing())
            {
                foreach (var item in PotentialTargetList.OrderBy(x => Vector3D.Distance(sourcePosition, EntityHelper.GetBlockPosition((IMySlimBlock)x))))
                {
                    if (m_constructionBlock.IsUserDefinedLimitReached())
                    {
                        m_lastInvalidTargetReason = "User defined maximum nanite limit reached";
                        return;
                    }

                    if (TargetList.Contains(item))
                    {
                        continue;
                    }

                    missing = inventoryManager.GetProjectionComponents((IMySlimBlock)item);
                    bool haveComponents = inventoryManager.CheckComponentsAvailable(ref missing, ref available);
                    if (haveComponents && NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this))
                    {
                        if (((IMySlimBlock)item).CubeGrid.GetPosition() == Vector3D.Zero)
                        {
                            m_lastInvalidTargetReason = "Target blocks grid is in an invalid position (Vector3D.Zero, this shouldn't happen!)";
                            continue;
                        }

                        var  blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid);
                        bool found     = false;
                        foreach (var block in blockList)
                        {
                            if (block.GetTarget <NaniteProjectionTargets>().TargetList.Contains(item))
                            {
                                found = true;
                                break;
                            }
                        }

                        if (found)
                        {
                            m_lastInvalidTargetReason = "Another factory has this block as a target";
                            continue;
                        }

                        TargetList.Add(item);
                        IMySlimBlock slimBlock = (IMySlimBlock)item;
                        var          def       = slimBlock.BlockDefinition as MyCubeBlockDefinition;
                        Logging.Instance.WriteLine(string.Format("ADDING Projection Target: conid={0} subtypeid={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, def.Id.SubtypeId, slimBlock.FatBlock != null ? slimBlock.FatBlock.EntityId : 0, slimBlock.Position));
                        if (TargetList.Count >= GetMaximumTargets())
                        {
                            break;
                        }
                    }
                    else if (!haveComponents)
                    {
                        m_lastInvalidTargetReason = "Missing components to start projected block";
                    }
                    else if (!NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this))
                    {
                        m_lastInvalidTargetReason = "Insufficient power for another target.";
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public int Update <T>(List <T> entityList)
        {
            if (entityList == null || entityList.Count == 0)
            {
                return(0);
            }

            object         val         = 0;
            IDbTransaction transaction = null;
            IDbConnection  connection  = null;

            try
            {
                //获取数据库连接,如果开启了事务,从事务中获取
                connection  = GetConnection();
                transaction = GetTransaction();

                T    firstEntity = entityList[0];
                Type classType   = firstEntity.GetType();

                PropertyInfo[] properties = ReflectionHelper.GetProperties(firstEntity.GetType());
                TableInfo      tableInfo  = EntityHelper.GetTableInfo(firstEntity, DbOperateType.UPDATE, properties);
                String         strSQL     = EntityHelper.GetUpdateSql(tableInfo);

                /*tableInfo.Columns.Add(tableInfo.Id.Key, tableInfo.Id.Value);
                 * IDbDataParameter[] parms = tableInfo.GetParameters();*/

                foreach (T entity in entityList)
                {
                    tableInfo = EntityHelper.GetTableInfo(entity, DbOperateType.UPDATE, properties);

                    List <IDbDataParameter> paramsList  = tableInfo.GetParameterList();
                    IDbDataParameter        dbParameter = DbFactory.CreateDbParameter(tableInfo.Id.Key, tableInfo.Id.Value);
                    paramsList.Add(dbParameter);

                    IDbDataParameter[] parms = tableInfo.GetParameters(paramsList);
                    val = AdoHelper.ExecuteNonQuery(connection, transaction, CommandType.Text, strSQL, parms);



                    /*if (AdoHelper.DbType == DatabaseType.ACCESS)
                     * {
                     *  strSQL = SQLBuilderHelper.builderAccessSQL(classType, tableInfo, strSQL, parms);
                     *  val = AdoHelper.ExecuteNonQuery(connection, CommandType.Text, strSQL);
                     * }
                     * else
                     * {
                     *  val = AdoHelper.ExecuteNonQuery(connection, CommandType.Text, strSQL, parms);
                     * }*/
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (m_Transaction == null)
                {
                    connection.Close();
                }
            }

            return(Convert.ToInt32(val));
        }
Ejemplo n.º 11
0
        public PageResult <T> FindPage <T>(string strSQL, ParamMap param) where T : new()
        {
            PageResult <T> pageResult = new PageResult <T>();
            List <T>       list       = new List <T>();
            IDataReader    sdr        = null;
            IDbConnection  connection = null;

            try
            {
                connection = GetConnection();
                bool closeConnection = GetWillConnectionState();

                strSQL = strSQL.ToLower();
                String countSQL = SQLBuilderHelper.builderCountSQL(strSQL);
                String columns  = SQLBuilderHelper.fetchColumns(strSQL);

                int count = this.Count(countSQL, param);

                T    entity    = new T();
                Type classType = entity.GetType();

                PropertyInfo[] properties = ReflectionHelper.GetProperties(classType);
                TableInfo      tableInfo  = EntityHelper.GetTableInfo(entity, DbOperateType.SELECT, properties);
                if (param.IsPage && !SQLBuilderHelper.isPage(strSQL))
                {
                    strSQL = SQLBuilderHelper.builderPageSQL(strSQL, param.OrderFields, param.IsDesc);
                }

                if (AdoHelper.DbType == DatabaseType.ACCESS)
                {
                    if (param.getInt("page_offset") > count)
                    {
                        int limit = param.getInt("page_limit") + count - param.getInt("page_offset");
                        if (limit > 0)
                        {
                            strSQL = SQLBuilderHelper.builderAccessPageSQL(strSQL, param, limit);
                            sdr    = AdoHelper.ExecuteReader(closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters());
                            list   = EntityHelper.toList <T>(sdr, tableInfo, properties);
                        }
                    }
                    else
                    {
                        strSQL = SQLBuilderHelper.builderAccessPageSQL(strSQL, param);
                        sdr    = AdoHelper.ExecuteReader(closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters());
                        list   = EntityHelper.toList <T>(sdr, tableInfo, properties);
                    }
                }
                else
                {
                    sdr  = AdoHelper.ExecuteReader(closeConnection, connection, CommandType.Text, strSQL, param.toDbParameters());
                    list = EntityHelper.toList <T>(sdr, tableInfo, properties);
                }
                pageResult.Total    = count;
                pageResult.DataList = list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sdr != null)
                {
                    sdr.Close();
                }
            }

            return(pageResult);
        }
Ejemplo n.º 12
0
        //<?xml version="1.0" encoding="utf-8"?>
        //<xml>
        //  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
        //  <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
        //  <CreateTime>1357986928</CreateTime>
        //  <MsgType><![CDATA[text]]></MsgType>
        //  <Content><![CDATA[中文]]></Content>
        //  <MsgId>5832509444155992350</MsgId>
        //</xml>

        /// <summary>
        /// 获取XDocument转换后的IRequestMessageBase实例。
        /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常
        /// </summary>
        /// <returns></returns>
        public static IRequestMessageBase GetRequestEntity(XDocument doc, PostModel postModel = null)
        {
            RequestMessageBase requestMessage = null;
            RequestMsgType     msgType;

            try
            {
                msgType = MsgTypeHelper.GetRequestMsgType(doc);
                switch (msgType)
                {
                case RequestMsgType.Text:
                    requestMessage = new RequestMessageText();
                    break;

                case RequestMsgType.Location:
                    requestMessage = new RequestMessageLocation();
                    break;

                case RequestMsgType.Image:
                    requestMessage = new RequestMessageImage();
                    break;

                case RequestMsgType.Voice:
                    requestMessage = new RequestMessageVoice();
                    break;

                case RequestMsgType.Video:
                    requestMessage = new RequestMessageVideo();
                    break;

                case RequestMsgType.Link:
                    requestMessage = new RequestMessageLink();
                    break;

                case RequestMsgType.Event:
                    //判断Event类型
                    switch (doc.Root.Element("Event").Value.ToUpper())
                    {
                    case "ENTER":        //进入会话
                        requestMessage = new RequestMessageEvent_Enter();
                        break;

                    case "LOCATION":        //地理位置
                        requestMessage = new RequestMessageEvent_Location();
                        break;

                    case "SUBSCRIBE":        //订阅(关注)
                        requestMessage = new RequestMessageEvent_Subscribe();
                        break;

                    case "UNSUBSCRIBE":        //取消订阅(关注)
                        requestMessage = new RequestMessageEvent_Unsubscribe();
                        break;

                    case "CLICK":        //菜单点击
                        requestMessage = new RequestMessageEvent_Click();
                        break;

                    case "SCAN":        //二维码扫描
                        requestMessage = new RequestMessageEvent_Scan();
                        break;

                    case "VIEW":        //URL跳转
                        requestMessage = new RequestMessageEvent_View();
                        break;

                    case "MASSSENDJOBFINISH":
                        requestMessage = new RequestMessageEvent_MassSendJobFinish();
                        break;

                    case "TEMPLATESENDJOBFINISH":        //模板信息
                        requestMessage = new RequestMessageEvent_TemplateSendJobFinish();
                        break;

                    case "SCANCODE_PUSH":        //扫码推事件(scancode_push)
                        requestMessage = new RequestMessageEvent_Scancode_Push();
                        break;

                    case "SCANCODE_WAITMSG":        //扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg)
                        requestMessage = new RequestMessageEvent_Scancode_Waitmsg();
                        break;

                    case "PIC_SYSPHOTO":        //弹出系统拍照发图(pic_sysphoto)
                        requestMessage = new RequestMessageEvent_Pic_Sysphoto();
                        break;

                    case "PIC_PHOTO_OR_ALBUM":        //弹出拍照或者相册发图(pic_photo_or_album)
                        requestMessage = new RequestMessageEvent_Pic_Photo_Or_Album();
                        break;

                    case "PIC_WEIXIN":        //弹出微信相册发图器(pic_weixin)
                        requestMessage = new RequestMessageEvent_Pic_Weixin();
                        break;

                    case "LOCATION_SELECT":        //弹出地理位置选择器(location_select)
                        requestMessage = new RequestMessageEvent_Location_Select();
                        break;

                    case "CARD_PASS_CHECK":        //卡券通过审核
                        requestMessage = new RequestMessageEvent_Card_Pass_Check();
                        break;

                    case "CARD_NOT_PASS_CHECK":        //卡券未通过审核
                        requestMessage = new RequestMessageEvent_Card_Not_Pass_Check();
                        break;

                    case "USER_GET_CARD":        //领取卡券
                        requestMessage = new RequestMessageEvent_User_Get_Card();
                        break;

                    case "USER_DEL_CARD":        //删除卡券
                        requestMessage = new RequestMessageEvent_User_Del_Card();
                        break;

                    default:        //其他意外类型(也可以选择抛出异常)
                        requestMessage = new RequestMessageEventBase();
                        break;
                    }
                    break;

                default:
                    throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在RequestMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());    //为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常
                }
                EntityHelper.FillEntityWithXml(requestMessage, doc);
            }
            catch (ArgumentException ex)
            {
                throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex);
            }
            return(requestMessage);
        }
        private void CreateActivity(int classId, Guid?refNoteID, string typeCode, Guid?owner)
        {
            var graphType = CRActivityPrimaryGraphAttribute.GetGraphType(classId);

            if (!PXAccess.VerifyRights(graphType))
            {
                throw new AccessViolationException(CR.Messages.FormNoAccessRightsMessage(graphType));
            }

            CRActivity activity = null;

            var cache = CreateInstanceCache <CRActivity>(graphType);

            if (cache == null)
            {
                return;
            }

            if (owner == null)
            {
                owner = EmployeeMaint.GetCurrentEmployeeID(cache.Graph);
            }

            Action <object> initializeHandler = delegate(object act1)
            {
                var act = act1 as CRActivity;
                if (act == null)
                {
                    return;
                }

                act.ClassID   = classId;
                act.RefNoteID = refNoteID;
                if (!string.IsNullOrEmpty(typeCode))
                {
                    act.Type = typeCode;
                }
                act.OwnerID = owner;
            };

            EntityHelper helper = new EntityHelper(cache.Graph);
            var          type   = helper.GetEntityRowType(refNoteID);
            var          entity = helper.GetEntityRow(type, refNoteID);

            Type entityGraphType = null;

            if (type != null)
            {
                PXPrimaryGraphAttribute.FindPrimaryGraph(cache.Graph.Caches[type], ref entity, out entityGraphType);
            }
            if (entityGraphType != null)
            {
                PXGraph entry = PXGraph.CreateInstance(entityGraphType);
                PXCache <CRActivity> activityCache = entry.Caches[typeof(CRActivity)] as PXCache <CRActivity>;
                if (activityCache != null)
                {
                    entry.Views[entry.PrimaryView].Cache.Current = entity;
                    activity = (CRActivity)activityCache.CreateInstance();
                    if (initializeHandler != null)
                    {
                        initializeHandler(activity);
                    }
                    activity = activityCache.InitNewRow(activity);
                }
            }

            if (activity == null)
            {
                activity = (CRActivity)cache.CreateInstance();

                initializeHandler(activity);

                activity = ((PXCache <CRActivity>)cache).InitNewRow(activity);
            }

            cache.Update(activity);
            PXRedirectHelper.TryRedirect(cache.Graph, PXRedirectHelper.WindowMode.NewWindow);
        }
Ejemplo n.º 14
0
        public void Add(
            DateTime date,
            bool useExistingBarcode,
            string barcode,
            bool isTransfer,
            string firstName,
            string LastName,
            DateTime dateOfBirth,
            int branchID,
            int packageID,
            DateTime?purchaseDate,
            DateTime effectiveDate,
            int billingTypeID,
            int billingCardTypeID,
            int billingBankID,
            string billingCardNo,
            string billingCardHolderName,
            string billingCardHolderID,
            DateTime cardExpiredDate,
            char status,
            int billingItemID,
            decimal duesAmount,
            DateTime?nextDuesDate,
            DateTime expiredDate,
            string homePhone,
            string cellphone,
            string mailingAddress,
            string zipCodeMailingAddress,
            string address,
            string zipCode,
            int areaID,
            int schoolID,
            bool fatherIsExist,
            string fatherName,
            string fatherIDCardNo,
            DateTime?fatherBirthDate,
            string fatherCellPhone,
            string fatherEmail,
            bool motherIsExist,
            string motherName,
            string motherIDCardNo,
            DateTime?motherBirthDate,
            string motherCellPhone,
            string motherEmail,
            string notes,
            string contractType)
        {
            PackageHeader package = ctx.PackageHeaders.SingleOrDefault(pkg => pkg.ID == packageID);

            if (package != null)
            {
                //nextDuesDate = effectiveDate.AddMonths(package.PackageDuesInMonth);
                Customer cust = null;
                if (useExistingBarcode)
                {
                    cust = ctx.Customers.Single(c => c.Barcode == barcode);
                }
                else
                {
                    cust                = new Customer();
                    cust.Barcode        = autoNumberProvider.Generate(branchID, "CU", 0, 0);
                    cust.FirstName      = firstName;
                    cust.LastName       = LastName;
                    cust.DateOfBirth    = dateOfBirth;
                    cust.HomeBranchID   = branchID;
                    cust.HomePhone      = homePhone;
                    cust.CellPhone1     = cellphone;
                    cust.BillingTypeID  = billingTypeID;
                    cust.AreaID         = areaID == 0 ? (int?)null : areaID;
                    cust.SchoolID       = schoolID == 0 ? (int?)null : schoolID;
                    cust.MailingAddress = mailingAddress;
                    cust.MailingZipCode = zipCodeMailingAddress;
                    cust.Address        = address;
                    cust.ZipCode        = zipCode;
                    if (billingTypeID != 1) // auto payment
                    {
                        cust.BankID           = billingBankID;
                        cust.CreditCardTypeID = billingCardTypeID;
                        cust.CardHolderName   = billingCardHolderName;
                        cust.CardHolderID     = billingCardHolderID;
                        cust.CardNo           = billingCardNo;
                        cust.ExpiredDate      = cardExpiredDate;
                    }
                    else
                    {
                        cust.BankID           = (int?)null;
                        cust.CreditCardTypeID = (int?)null;
                        cust.CardHolderName   = null;
                        cust.CardHolderID     = null;
                        cust.CardNo           = null;
                        cust.ExpiredDate      = (DateTime?)null;
                    }
                    EntityHelper.SetAuditFieldForInsert(cust, HttpContext.Current.User.Identity.Name);
                    ctx.Customers.InsertOnSubmit(cust);

                    autoNumberProvider.Increment("CU", branchID, 0);
                }

                Contract contract = new Contract();
                contract.ContractNo    = autoNumberProvider.Generate(branchID, "CO", date.Month, date.Year);
                contract.Date          = date;
                contract.Customer      = cust;
                contract.BranchID      = branchID;
                contract.PackageHeader = package;
                //contract.PurchaseDate = purchaseDate;
                contract.EffectiveDate = effectiveDate;
                contract.BillingItemID = billingItemID == 0 ? (int?)null : billingItemID;
                contract.DuesAmount    = duesAmount;
                contract.NextDuesDate  = nextDuesDate.Value;
                //contract.ExpiredDate = expiredDate;
                contract.ExpiredDate   = effectiveDate.AddMonths(package.PackageDuesInMonth);
                contract.BillingTypeID = billingTypeID;
                contract.Status        = status.ToString();
                contract.Notes         = notes;
                contract.DuesInMonth   = package.PackageDuesInMonth;
                if (isTransfer)
                {
                    contract.ContractType = "T";
                }
                else
                {
                    contract.ContractType = useExistingBarcode ? contractType : null;
                }
                EntityHelper.SetAuditFieldForInsert(contract, HttpContext.Current.User.Identity.Name);
                ctx.Contracts.InsertOnSubmit(contract);


                if (!useExistingBarcode)
                {
                    if (fatherIsExist)
                    {
                        Person person = new Person();
                        person.Connection = "F";
                        person.Name       = fatherName;
                        person.IDCardNo   = fatherIDCardNo;
                        person.Phone1     = fatherCellPhone;
                        person.BirthDate  = fatherBirthDate;
                        person.Email      = fatherEmail;
                        person.Customer   = cust;
                        EntityHelper.SetAuditFieldForInsert(person, HttpContext.Current.User.Identity.Name);
                        ctx.Persons.InsertOnSubmit(person);
                    }

                    if (motherIsExist)
                    {
                        Person person = new Person();
                        person.Connection = "M";
                        person.Name       = motherName;
                        person.IDCardNo   = motherIDCardNo;
                        person.Phone1     = motherCellPhone;
                        person.BirthDate  = motherBirthDate;
                        person.Email      = motherEmail;
                        person.Customer   = cust;
                        EntityHelper.SetAuditFieldForInsert(person, HttpContext.Current.User.Identity.Name);
                        ctx.Persons.InsertOnSubmit(person);
                    }
                }

                autoNumberProvider.Increment("CO", branchID, date.Year);
                ctx.SubmitChanges();
            }
        }
Ejemplo n.º 15
0
        public void Update(
            int id,
            int packageID,
            DateTime date,
            DateTime effectiveDate,
            int billingTypeID,
            int billingCardTypeID,
            int billingBankID,
            string billingCardNo,
            string billingCardHolderName,
            string billingCardHolderID,
            DateTime cardExpiredDate,
            string homePhone,
            string cellphone,
            string mailingAddress,
            string zipCodeMailingAddress,
            string address,
            string zipCode,
            int areaID,
            int schoolID,
            int billingItemID,
            decimal duesAmount,
            DateTime nextDuesDate,
            DateTime expiredDate,
            bool fatherIsExist,
            string fatherName,
            string fatherIDCardNo,
            DateTime?fatherBirthDate,
            string fatherCellPhone,
            string fatherEmail,
            bool motherIsExist,
            string motherName,
            string motherIDCardNo,
            DateTime?motherBirthDate,
            string motherCellPhone,
            string motherEmail,
            string notes)
        {
            //DateTime nextDuesDate;
            PackageHeader package = ctx.PackageHeaders.SingleOrDefault(pkg => pkg.ID == packageID);

            if (package != null)
            {
                //nextDuesDate = effectiveDate.AddMonths(package.PackageDuesInMonth);

                Contract contract = ctx.Contracts.Single(row => row.ID == id);
                contract.PackageID     = packageID;
                contract.Date          = date;
                contract.EffectiveDate = effectiveDate;
                contract.BillingTypeID = billingTypeID;
                contract.BillingItemID = billingItemID == 0 ? (int?)null : billingItemID;
                contract.NextDuesDate  = nextDuesDate;
                contract.ExpiredDate   = expiredDate; //effectiveDate.AddMonths(package.PackageDuesInMonth);
                contract.Notes         = notes;
                contract.DuesAmount    = duesAmount;
                contract.DuesInMonth   = package.PackageDuesInMonth;

                Customer customer = contract.Customer;
                customer.HomePhone      = homePhone;
                customer.CellPhone1     = cellphone;
                customer.MailingAddress = mailingAddress;
                customer.MailingZipCode = zipCodeMailingAddress;
                customer.BillingTypeID  = billingTypeID;
                customer.Address        = address;
                customer.ZipCode        = zipCode;
                customer.AreaID         = areaID == 0 ? (int?)null : areaID;
                customer.SchoolID       = schoolID == 0 ? (int?)null : schoolID;
                if (billingTypeID != 1) // manual payment
                {
                    customer.BankID           = billingBankID;
                    customer.CreditCardTypeID = billingCardTypeID;
                    customer.CardHolderName   = billingCardHolderName;
                    customer.CardHolderID     = billingCardHolderID;
                    customer.CardNo           = billingCardNo;
                    customer.ExpiredDate      = cardExpiredDate;
                }
                else
                {
                    customer.BankID           = (int?)null;
                    customer.CreditCardTypeID = (int?)null;
                    customer.CardHolderName   = null;
                    customer.CardHolderID     = null;
                    customer.CardNo           = null;
                    customer.ExpiredDate      = (DateTime?)null;
                }
                EntityHelper.SetAuditFieldForUpdate(customer, HttpContext.Current.User.Identity.Name);

                if (fatherIsExist)
                {
                    Person person = ctx.Persons.Any(p => p.Connection == "F" && p.CustomerID == contract.CustomerID) ? ctx.Persons.Single(p => p.Connection == "F" && p.CustomerID == contract.CustomerID) : new Person();
                    person.Connection = "F";
                    person.Name       = fatherName;
                    person.IDCardNo   = fatherIDCardNo;
                    person.Phone1     = fatherCellPhone;
                    person.BirthDate  = fatherBirthDate;
                    person.Email      = fatherEmail;
                    if (person.ID == 0)
                    {
                        person.Customer = customer;
                        EntityHelper.SetAuditFieldForInsert(person, HttpContext.Current.User.Identity.Name);
                        ctx.Persons.InsertOnSubmit(person);
                    }
                    else
                    {
                        EntityHelper.SetAuditFieldForUpdate(person, HttpContext.Current.User.Identity.Name);
                    }
                }

                if (motherIsExist)
                {
                    Person person = ctx.Persons.Any(p => p.Connection == "M" && p.CustomerID == contract.CustomerID) ? ctx.Persons.Single(p => p.Connection == "M" && p.CustomerID == contract.CustomerID) : new Person();
                    person.Connection = "M";
                    person.Name       = motherName;
                    person.IDCardNo   = motherIDCardNo;
                    person.Phone1     = motherCellPhone;
                    person.BirthDate  = motherBirthDate;
                    person.Email      = motherEmail;
                    if (person.ID == 0)
                    {
                        person.Customer = customer;
                        EntityHelper.SetAuditFieldForInsert(person, HttpContext.Current.User.Identity.Name);
                        ctx.Persons.InsertOnSubmit(person);
                    }
                    else
                    {
                        EntityHelper.SetAuditFieldForUpdate(person, HttpContext.Current.User.Identity.Name);
                    }
                }

                EntityHelper.SetAuditFieldForUpdate(contract, HttpContext.Current.User.Identity.Name);
                ctx.SubmitChanges();
            }
        }
 /// <summary>
 /// 将ResponseMessage实体转为XML
 /// </summary>
 /// <param name="entity">ResponseMessage实体</param>
 /// <returns></returns>
 public static XDocument ConvertEntityToXml(ResponseMessageBase entity)
 {
     return(EntityHelper.ConvertEntityToXml(entity));
 }
Ejemplo n.º 17
0
        /// <summary>
        /// 查询WorkSet
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="WorkSet_Id">表格编号</param>
        /// <param name="myParameters">参数列表</param>
        /// <returns></returns>
        public static List <T> Open <T>(string WorkSet_Id, List <MyParameter> myParameters) where T : new()
        {
            DataTable dt = Open(WorkSet_Id, myParameters);

            return(EntityHelper.GetEntities <T>(dt));
        }
Ejemplo n.º 18
0
        public int Insert <T>(T entity)
        {
            if (entity == null)
            {
                return(0);
            }

            object val = 0;

            IDbTransaction transaction = null;
            IDbConnection  connection  = null;

            try
            {
                //获取数据库连接,如果开启了事务,从事务中获取
                connection  = GetConnection();
                transaction = GetTransaction();

                Type classType = entity.GetType();
                //从实体对象的属性配置上获取对应的表信息
                PropertyInfo[] properties = ReflectionHelper.GetProperties(classType);
                TableInfo      tableInfo  = EntityHelper.GetTableInfo(entity, DbOperateType.INSERT, properties);

                //获取SQL语句
                String strSql = EntityHelper.GetInsertSql(tableInfo);

                //获取参数
                IDbDataParameter[] parms = tableInfo.GetParameters();
                //执行Insert命令
                val = AdoHelper.ExecuteScalar(connection, transaction, CommandType.Text, strSql, parms);

                //Access数据库执行不需要命名参数
                if (AdoHelper.DbType == DatabaseType.ACCESS)
                {
                    //如果是Access数据库,另外执行获取自动生成的ID
                    String autoSql = EntityHelper.GetAutoSql();
                    val = AdoHelper.ExecuteScalar(connection, transaction, CommandType.Text, autoSql);
                }

                //把自动生成的主键ID赋值给返回的对象
                if (!tableInfo.NoAutomaticKey)
                {
                    if (AdoHelper.DbType == DatabaseType.SQLSERVER || AdoHelper.DbType == DatabaseType.MYSQL || AdoHelper.DbType == DatabaseType.ACCESS || AdoHelper.DbType == DatabaseType.SQLITE)
                    {
                        PropertyInfo propertyInfo = EntityHelper.GetPrimaryKeyPropertyInfo(entity, properties);
                        ReflectionHelper.SetPropertyValue(entity, propertyInfo, val);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (m_Transaction == null)
                {
                    connection.Close();
                }
            }

            return(Convert.ToInt32(val));
        }
Ejemplo n.º 19
0
 public static object FilterPK(string id)
 {
     return(new JArray(new object[] { $"{EntityHelper.GetDbTableName<TEntity>()}.{EntityHelper.GetPKColumnName<TEntity>()}='{id}'" }));
 }
 public override void CacheAttached(PXCache sender)
 {
     entityHelper = new EntityHelper(sender.Graph);
 }
Ejemplo n.º 21
0
        EntityInfo GetSourceEntityInfo(int productId, string locale)
        {
            var sourceEntityType = Profile["LastViewedEntityName"] != null
                                ? Profile["LastViewedEntityName"].ToString()
                                : string.Empty;

            var sourceEntityName = Profile["LastViewedEntityInstanceName"] != null
                                ? Profile["LastViewedEntityInstanceName"].ToString()
                                : string.Empty;

            var sourceEntityIdString = Profile["LastViewedEntityInstanceID"] != null
                                ? Profile["LastViewedEntityInstanceID"].ToString()
                                : string.Empty;

            int sourceEntityId;

            if (!int.TryParse(sourceEntityIdString, out sourceEntityId))
            {
                sourceEntityId = 0;
            }

            // validate that source entity id is actually valid for this product:
            if (sourceEntityId != 0)
            {
                var sqlParameters = new SqlParameter[] {
                    new SqlParameter(
                        "AllowEntityFiltering",
                        AppLogic.GlobalConfigBool("AllowEntityFiltering")
                                                        ? 1
                                                        : 0),
                    new SqlParameter("StoreId", AppLogic.StoreID()),
                    new SqlParameter("ProductId", productId),
                    new SqlParameter("SourceEntityId", sourceEntityId),
                    new SqlParameter("SourceEntityType", sourceEntityType)
                };

                var sql = @"select count(*) as N from productentity a with (nolock) 
					inner join (select distinct a.entityid, a.EntityType from productentity a with (nolock) 
						left join EntityStore b with (nolock) on a.EntityID = b.EntityID 
						where (@AllowEntityFiltering = 0 or StoreID = @StoreId)
					) b on a.EntityID = b.EntityID and a.EntityType=b.EntityType 
					where ProductID = @ProductId 
					and a.EntityID = @SourceEntityId 
					and a.EntityType = @SourceEntityType"                    ;

                if (DB.GetSqlN(sql, sqlParameters) == 0)
                {
                    sourceEntityId = 0;
                }
            }

            if (sourceEntityId == 0)
            {
                //We had no entity context coming in, try to find an entity context for this product
                foreach (var entityType in new string[] { "Category", "Section", "Manufacturer" })
                {
                    sourceEntityId = EntityHelper.GetProductsFirstEntity(productId, entityType);
                    if (sourceEntityId > 0)
                    {
                        var entityHelper = AppLogic.LookupHelper(entityType, 0);
                        var entityName   = entityHelper.GetEntityName(sourceEntityId, locale);
                        sourceEntityType = entityType;
                        sourceEntityName = entityName;
                        break;
                    }
                }
            }

            return(new EntityInfo(
                       id: sourceEntityId,
                       type: sourceEntityType,
                       name: sourceEntityName));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGroupMembersGrid()
        {
            if (_group != null)
            {
                pnlGroupMembers.Visible = true;

                lHeading.Text = string.Format("{0} {1}", _group.GroupType.GroupTerm, _group.GroupType.GroupMemberTerm.Pluralize());

                if (_group.GroupType.Roles.Any())
                {
                    nbRoleWarning.Visible = false;
                    rFilter.Visible       = true;
                    gGroupMembers.Visible = true;

                    var rockContext = new RockContext();

                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                    var qry = groupMemberService.Queryable("Person,GroupRole", true)
                              .Where(m => m.GroupId == _group.Id);

                    // Filter by First Name
                    string firstName = tbFirstName.Text;
                    if (!string.IsNullOrWhiteSpace(firstName))
                    {
                        qry = qry.Where(m => m.Person.FirstName.StartsWith(firstName));
                    }

                    // Filter by Last Name
                    string lastName = tbLastName.Text;
                    if (!string.IsNullOrWhiteSpace(lastName))
                    {
                        qry = qry.Where(m => m.Person.LastName.StartsWith(lastName));
                    }

                    // Filter by role
                    var validGroupTypeRoles = _group.GroupType.Roles.Select(r => r.Id).ToList();
                    var roles = new List <int>();
                    foreach (string role in cblRole.SelectedValues)
                    {
                        if (!string.IsNullOrWhiteSpace(role))
                        {
                            int roleId = int.MinValue;
                            if (int.TryParse(role, out roleId) && validGroupTypeRoles.Contains(roleId))
                            {
                                roles.Add(roleId);
                            }
                        }
                    }
                    if (roles.Any())
                    {
                        qry = qry.Where(m => roles.Contains(m.GroupRoleId));
                    }

                    // Filter by Status
                    var statuses = new List <GroupMemberStatus>();
                    foreach (string status in cblStatus.SelectedValues)
                    {
                        if (!string.IsNullOrWhiteSpace(status))
                        {
                            statuses.Add(status.ConvertToEnum <GroupMemberStatus>());
                        }
                    }
                    if (statuses.Any())
                    {
                        qry = qry.Where(m => statuses.Contains(m.GroupMemberStatus));
                    }

                    // Filter the query using any configured attribute filters.
                    if (AvailableAttributes != null && AvailableAttributes.Any())
                    {
                        // Get a reference to the parameter accepted by the Query expression.
                        var methodCallExpression = (MethodCallExpression)qry.Expression;

                        var lambdaDelegate = Expression.Lambda <Func <LambdaExpression> >(methodCallExpression.Arguments[1]).Compile();

                        var lambdaExpression = (Expression <Func <GroupMember, bool> >)(lambdaDelegate.Invoke());

                        var queryParameter = lambdaExpression.Parameters[0];

                        // Add a condition for each of the specified attribute values.
                        foreach (var attribute in AvailableAttributes)
                        {
                            var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());

                            if (filterControl != null)
                            {
                                var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues);

                                var entityField = EntityHelper.GetEntityFieldForAttribute(attribute);

                                var filterExpression = EntityFieldFilter.CreateAttributeExpression(groupMemberService, queryParameter, entityField, filterValues);

                                if (filterExpression == null)
                                {
                                    continue;
                                }

                                qry = qry.Where(queryParameter, filterExpression);
                            }
                        }
                    }

                    _inactiveStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);

                    SortProperty sortProperty = gGroupMembers.SortProperty;

                    List <GroupMember> groupMembers = null;

                    if (sortProperty != null)
                    {
                        groupMembers = qry.Sort(sortProperty).ToList();
                    }
                    else
                    {
                        groupMembers = qry.OrderBy(a => a.GroupRole.Order).ThenBy(a => a.Person.LastName).ThenBy(a => a.Person.FirstName).ToList();
                    }

                    // Since we're not binding to actual group member list, but are using AttributeField columns,
                    // we need to save the display data into the grid's object list
                    gGroupMembers.ObjectList = new Dictionary <string, object>();
                    groupMembers.ForEach(m => gGroupMembers.ObjectList.Add(m.Id.ToString(), m));

                    gGroupMembers.DataSource = groupMembers.Select(m => new
                    {
                        m.Id,
                        m.Guid,
                        m.PersonId,
                        Name      = m.Person.NickName + " " + m.Person.LastName,
                        GroupRole = m.GroupRole.Name,
                        m.GroupMemberStatus,
                        ConnectionStatus = m.Person.ConnectionStatusValue.Value
                    }).ToList();

                    gGroupMembers.DataBind();
                }
                else
                {
                    nbRoleWarning.Text = string.Format(
                        "{0} cannot be added to this {1} because the '{2}' group type does not have any roles defined.",
                        _group.GroupType.GroupMemberTerm.Pluralize(),
                        _group.GroupType.GroupTerm,
                        _group.GroupType.Name);

                    nbRoleWarning.Visible = true;
                    rFilter.Visible       = false;
                    gGroupMembers.Visible = false;
                }
            }
            else
            {
                pnlGroupMembers.Visible = false;
            }
        }
Ejemplo n.º 23
0
        private void ProcessProjectedItem(IMySlimBlock target)
        {
            if (Sync.IsServer)
            {
                if (target.CubeGrid.GetPosition() == Vector3D.Zero)
                {
                    Logging.Instance.WriteLine("CANCELLING Projection Target due to invalid position");
                    CancelTarget(target);
                    return;
                }

                if (!IsEnabled())
                {
                    Logging.Instance.WriteLine("CANCELLING Projection Target due to being disabled");
                    CancelTarget(target);
                    return;
                }

                if (!NaniteConstructionPower.HasRequiredPowerForCurrentTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock))
                {
                    Logging.Instance.WriteLine("CANCELLING Projection Target due to power shortage");
                    CancelTarget(target);
                    return;
                }

                if (m_constructionBlock.FactoryState != NaniteConstructionBlock.FactoryStates.Active)
                {
                    return;
                }

                double distance = EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, target);
                int    time     = (int)Math.Max(GetMinTravelTime() * 1000f, (distance / GetSpeed()) * 1000f);
                if (!m_targetBlocks.ContainsKey(target))
                {
                    NaniteProjectionTarget projectionTarget = new NaniteProjectionTarget();
                    projectionTarget.ParticleCount = 0;
                    projectionTarget.StartTime     = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds;
                    m_targetBlocks.Add(target, projectionTarget);
                    m_constructionBlock.SendAddTarget(target, TargetTypes.Projection, GetProjectorByBlock(target));
                }

                if (MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_targetBlocks[target].StartTime >= time / 2.5 && !m_targetBlocks[target].CheckInventory)
                {
                    m_targetBlocks[target].CheckInventory = true;
                    if (!m_constructionBlock.InventoryManager.ProcessMissingComponents(target))
                    {
                        Logging.Instance.WriteLine("CANCELLING Projection Target due to missing components");
                        CancelTarget(target);
                        return;
                    }
                }

                if (MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_targetBlocks[target].StartTime >= time / 2)
                {
                    //BuildBlock(target, (MyCubeBlock)m_constructionBlock.ConstructionBlock);
                    ProcessBuildBlock(target);
                    CompleteTarget(target);
                    return;
                }

                if (!m_potentialTargetList.Contains(target))
                {
                    Logging.Instance.WriteLine("COMPLETING Projection Target since potential target is missing");
                    CompleteTarget(target);
                    return;
                }
            }

            CreateProjectionParticle(target);
        }
Ejemplo n.º 24
0
 public static void RepairVehicle(Client getter) =>
 EntityHelper.GetVehicle(getter.Vehicle)?.Repair();
Ejemplo n.º 25
0
        public override void ParallelUpdate(List <IMyCubeGrid> gridList, List <IMySlimBlock> gridBlocks)
        {
            try
            {
                if (!IsEnabled())
                {
                    PotentialTargetList.Clear();
                    return;
                }

                // Add
                foreach (var beaconBlock in NaniteConstructionManager.BeaconList.Where(x => x is NaniteBeaconDeconstruct && Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), x.BeaconBlock.GetPosition()) < m_maxDistance * m_maxDistance))
                {
                    IMyCubeBlock item = (IMyCubeBlock)beaconBlock.BeaconBlock;

                    if (!((IMyFunctionalBlock)item).Enabled || !((IMyFunctionalBlock)item).IsFunctional)
                    {
                        continue;
                    }

                    if (gridList.Contains(item.CubeGrid))
                    {
                        continue;
                    }

                    MyRelationsBetweenPlayerAndBlock relation = item.GetUserRelationToOwner(m_constructionBlock.ConstructionBlock.OwnerId);
                    if (!(relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.FactionShare || (MyAPIGateway.Session.CreativeMode && relation == MyRelationsBetweenPlayerAndBlock.NoOwnership)))
                    {
                        continue;
                    }

                    if (m_validBeaconedGrids.FirstOrDefault(x => x.GridsProcessed.Contains(item.CubeGrid)) != null)
                    {
                        continue;
                    }

                    NaniteDeconstructionGrid deconstruct = new NaniteDeconstructionGrid(item.CubeGrid);
                    m_validBeaconedGrids.Add(deconstruct);
                    CreateGridStack(deconstruct, (MyCubeGrid)item.CubeGrid, (MyCubeBlock)item);

                    using (Lock.AcquireExclusiveUsing())
                    {
                        foreach (var slimBlock in deconstruct.RemoveList)
                        {
                            PotentialTargetList.Add(slimBlock);
                        }
                    }

                    deconstruct.RemoveList.Clear();
                }

                CheckAreaBeacons();
                if (PotentialTargetList.Count > 0)
                {
                    using (Lock.AcquireExclusiveUsing())
                    {
                        foreach (IMySlimBlock item in PotentialTargetList.ToList())
                        {
                            if (item.CubeGrid.Closed || item.IsDestroyed || item.IsFullyDismounted || (item.FatBlock != null && item.FatBlock.Closed))
                            {
                                PotentialTargetList.Remove(item);
                            }

                            if (EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, item) > m_maxDistance)
                            {
                                PotentialTargetList.Remove(item);
                            }
                        }

                        //m_potentialTargetList = m_potentialTargetList.OrderBy(x => GetBlockConnections((IMySlimBlock)(x))).ToList();
                    }
                }
                else if (TargetList.Count == 0 && PotentialTargetList.Count == 0)
                {
                    m_validBeaconedGrids.Clear();
                }
            }
            catch (Exception ex)
            {
                Logging.Instance.WriteLine(string.Format("Parallel Erorr: {0}", ex.ToString()));
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Gets the Entity type based on the entity logical name.
 /// </summary>
 /// <param name="entityLogicalName">Name of the entity logical.</param>
 /// <returns></returns>
 public static Type GetType(string entityLogicalName)
 {
     return(EntityHelper.GetType(TestSettings.EarlyBound.Assembly, TestSettings.EarlyBound.Namespace, entityLogicalName));
 }
Ejemplo n.º 27
0
        public async Task UpdateUserAsync_Success()
        {
            // Arrange
            var helper  = new TestHelper();
            var service = helper.Create <PimsKeycloakService>();

            var euser      = EntityHelper.CreateUser("test");
            var removeRole = euser.Roles.First().Role;

            removeRole.KeycloakGroupId = Guid.NewGuid();

            var keycloakServiceMock = helper.GetMock <Pims.Keycloak.IKeycloakService>();
            var kuser = new Pims.Keycloak.Models.UserModel()
            {
                Id       = euser.Id,
                Username = euser.Username,
                Groups   = new string[] { removeRole.KeycloakGroupId.ToString() }
            };

            keycloakServiceMock.Setup(m => m.GetUserAsync(It.IsAny <Guid>())).ReturnsAsync(kuser);
            keycloakServiceMock.Setup(m => m.GetUserGroupsAsync(euser.Id))
            .ReturnsAsync(kuser.Groups.Select(g => new Pims.Keycloak.Models.GroupModel()
            {
                Id = new Guid(g)
            }).ToArray());
            keycloakServiceMock.Setup(m => m.UpdateUserAsync(It.IsAny <Pims.Keycloak.Models.UserModel>()));

            var pimsAdminServiceMock = helper.GetMock <Pims.Dal.Services.Admin.IPimsAdminService>();

            pimsAdminServiceMock.Setup(m => m.User.Get(It.IsAny <Guid>())).Returns(euser);
            pimsAdminServiceMock.Setup(m => m.Role.Find(removeRole.Id)).Returns(removeRole);

            var user    = EntityHelper.CreateUser(euser.Id, euser.Username, "new first name", "new last name");
            var addRole = user.Roles.First().Role;

            addRole.KeycloakGroupId = Guid.NewGuid();
            pimsAdminServiceMock.Setup(m => m.Role.Find(addRole.Id)).Returns(addRole);

            var pimsServiceMock = helper.GetMock <IPimsService>();

            pimsServiceMock.Setup(m => m.User.GetAgencies(It.IsAny <Guid>())).Returns(euser.Agencies.Select(a => a.AgencyId));

            // Act
            var result = await service.UpdateUserAsync(user);

            // Assert
            result.Id.Should().Be(user.Id);
            result.Username.Should().Be(user.Username);
            result.FirstName.Should().Be(user.FirstName);
            result.LastName.Should().Be(user.LastName);
            result.Agencies.Count.Should().Be(euser.Agencies.Count);
            result.Roles.Count.Should().Be(1);
            result.Roles.First().Role.KeycloakGroupId.Should().Be(user.Roles.First().Role.KeycloakGroupId);

            keycloakServiceMock.Verify(m => m.GetUserGroupsAsync(euser.Id), Times.Once);
            keycloakServiceMock.Verify(m => m.RemoveGroupFromUserAsync(euser.Id, new Guid(kuser.Groups.First())), Times.Once);
            keycloakServiceMock.Verify(m => m.AddGroupToUserAsync(euser.Id, addRole.KeycloakGroupId.Value), Times.Once);
            pimsAdminServiceMock.Verify(m => m.User.Update(It.IsAny <Entity.User>()), Times.Once);
            pimsServiceMock.Verify(m => m.User.GetAgencies(It.IsAny <Guid>()), Times.Once);
            keycloakServiceMock.Verify(m => m.UpdateUserAsync(It.IsAny <Pims.Keycloak.Models.UserModel>()), Times.Once);
        }
    public static IServiceCollection AddDefaultRepository(
        this IServiceCollection services,
        Type entityType,
        Type repositoryImplementationType,
        bool replaceExisting = false)
    {
        //IReadOnlyBasicRepository<TEntity>
        var readOnlyBasicRepositoryInterface = typeof(IReadOnlyBasicRepository <>).MakeGenericType(entityType);

        if (readOnlyBasicRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
        {
            RegisterService(services, readOnlyBasicRepositoryInterface, repositoryImplementationType, replaceExisting);

            //IReadOnlyRepository<TEntity>
            var readOnlyRepositoryInterface = typeof(IReadOnlyRepository <>).MakeGenericType(entityType);
            if (readOnlyRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
            {
                RegisterService(services, readOnlyRepositoryInterface, repositoryImplementationType, replaceExisting);
            }

            //IBasicRepository<TEntity>
            var basicRepositoryInterface = typeof(IBasicRepository <>).MakeGenericType(entityType);
            if (basicRepositoryInterface.IsAssignableFrom(repositoryImplementationType))
            {
                RegisterService(services, basicRepositoryInterface, repositoryImplementationType, replaceExisting);

                //IRepository<TEntity>
                var repositoryInterface = typeof(IRepository <>).MakeGenericType(entityType);
                if (repositoryInterface.IsAssignableFrom(repositoryImplementationType))
                {
                    RegisterService(services, repositoryInterface, repositoryImplementationType, replaceExisting);
                }
            }
        }

        var primaryKeyType = EntityHelper.FindPrimaryKeyType(entityType);

        if (primaryKeyType != null)
        {
            //IReadOnlyBasicRepository<TEntity, TKey>
            var readOnlyBasicRepositoryInterfaceWithPk = typeof(IReadOnlyBasicRepository <,>).MakeGenericType(entityType, primaryKeyType);
            if (readOnlyBasicRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
            {
                RegisterService(services, readOnlyBasicRepositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);

                //IReadOnlyRepository<TEntity, TKey>
                var readOnlyRepositoryInterfaceWithPk = typeof(IReadOnlyRepository <,>).MakeGenericType(entityType, primaryKeyType);
                if (readOnlyRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
                {
                    RegisterService(services, readOnlyRepositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);
                }

                //IBasicRepository<TEntity, TKey>
                var basicRepositoryInterfaceWithPk = typeof(IBasicRepository <,>).MakeGenericType(entityType, primaryKeyType);
                if (basicRepositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
                {
                    RegisterService(services, basicRepositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);

                    //IRepository<TEntity, TKey>
                    var repositoryInterfaceWithPk = typeof(IRepository <,>).MakeGenericType(entityType, primaryKeyType);
                    if (repositoryInterfaceWithPk.IsAssignableFrom(repositoryImplementationType))
                    {
                        RegisterService(services, repositoryInterfaceWithPk, repositoryImplementationType, replaceExisting);
                    }
                }
            }
        }

        return(services);
    }
Ejemplo n.º 29
0
        protected void MergeDuplicates(int targetID, List <TMain> duplicateEntities, List <FieldValue> values, bool IsContractBasedAPI)
        {
            TMain targetEntity = GetTargetEntity(targetID);

            object realTargetEntity = targetEntity;
            var    graphType        = new EntityHelper(Base).GetPrimaryGraphType(ref realTargetEntity, false);

            if (graphType == null)
            {
                return;
            }

            PXGraph targetGraph = PXGraph.CreateInstance(graphType);

            PXCache cache = targetGraph.Caches[typeof(TMain)];

            var refNoteIdField = EntityHelper.GetNoteField(cache.GetItemType());

            realTargetEntity = cache.CreateCopy(realTargetEntity);

            Contact targetContact = GetTargetContact(targetEntity);
            Address targetAddress = GetTargetAddress(targetEntity);

            Dictionary <Type, object> targets = new Dictionary <Type, object>
            {
                [typeof(TMain)]   = realTargetEntity,
                [typeof(Contact)] = targetContact,
                [typeof(Address)] = targetAddress
            };

            foreach (FieldValue fieldValue in values)
            {
                if (fieldValue.AttributeID == null)
                {
                    Type         type  = Type.GetType(fieldValue.CacheName);
                    PXFieldState state = (PXFieldState)targetGraph.Caches[type].GetStateExt(targets[type], fieldValue.Name);
                    if (state == null || !Equals(state.Value, fieldValue.Value))
                    {
                        targetGraph.Caches[type].SetValueExt(targets[type], fieldValue.Name, fieldValue.Value);
                        targets[type] = targetGraph.Caches[type].CreateCopy(targetGraph.Caches[type].Update(targets[type]));
                    }
                }
                else
                {
                    PXCache   attrCache = cache.Graph.Caches[typeof(CSAnswers)];
                    CSAnswers attr      = new CSAnswers
                    {
                        AttributeID = fieldValue.AttributeID,
                        RefNoteID   = cache.GetValue(targetEntity, refNoteIdField) as Guid?,
                        Value       = fieldValue.Value,
                    };

                    Dictionary <string, object> keys = new Dictionary <string, object>();
                    foreach (string key in attrCache.Keys.ToArray())
                    {
                        keys[key] = attrCache.GetValue(attr, key);
                    }


                    if (attrCache.Locate(keys) == 0)
                    {
                        attrCache.Insert(attr);
                    }
                    else
                    {
                        var located = attrCache.Locate(attr) as CSAnswers;
                        located.Value = attr.Value;
                        attrCache.Update(located);
                    }
                }
            }

            PXPrimaryGraphCollection primaryGraph = new PXPrimaryGraphCollection(targetGraph);

            using (PXTransactionScope scope = new PXTransactionScope())
            {
                foreach (TMain duplicateEntity in duplicateEntities)
                {
                    // only int, only single field
                    if (cache.GetValue(duplicateEntity, cache.Keys[0]) as int? == targetID)
                    {
                        continue;
                    }

                    targetGraph.Caches[realTargetEntity.GetType()].Current = realTargetEntity;

                    MergeEntities(targetGraph, realTargetEntity as TMain, duplicateEntity);

                    targetGraph.Actions.PressSave();

                    PXGraph operGraph = primaryGraph[duplicateEntity];

                    RunActionWithAppliedAutomation(operGraph, duplicateEntity, nameof(CloseAsDuplicate));

                    operGraph.Actions.PressSave();
                }

                scope.Complete();
            }

            // should become validated if no possible duplicates
            Base.Views[Base.PrimaryView].Cache.Current = targetEntity;

            Base.Actions.PressCancel();

            RunActionWithAppliedAutomation(Base, targetEntity, nameof(CheckForDuplicates));

            if (!IsContractBasedAPI)
            {
                RunActionWithAppliedAutomation(targetGraph, realTargetEntity, "Cancel");

                throw new PXRedirectRequiredException(targetGraph, "");
            }
        }
Ejemplo n.º 30
0
        public string AddOrUpdateReceiving(int id, int poID, DateTime date, string goodIssueNo,
                                           string freightInfo, string notes, List <ReceivingDetailViewModel> detail)
        {
            List <ReceivingDetail> receivingDetails =
                context.ReceivingHeaders
                .Where(rcv => rcv.PurchaseOrderID == poID && rcv.ID != id && !rcv.VoidDate.HasValue)
                .SelectMany(x => x.ReceivingDetails)
                .ToList();
            var order = context.PurchaseOrderHeaders.Single(po => po.ID == poID && !po.VoidDate.HasValue);
            List <PurchaseOrderDetail> orderDetails = order.PurchaseOrderDetails.ToList();

            var receiveHeader = id == 0
              ? new ReceivingHeader()
              : context.ReceivingHeaders.Single(rh => rh.ID == id);

            var autoNo = new AutoNumberProvider(context, principal);
            var emp    = new EmployeeProvider(context, principal);

            if (id == 0)
            {
                receiveHeader.DocumentNo = autoNo.GenerateReceivingRunningNumber(CurrentCompanyCode, date);
            }

            receiveHeader.PurchaseOrderID = poID;
            receiveHeader.Date            = date;
            receiveHeader.GoodIssueNo     = goodIssueNo;
            receiveHeader.FreightInfo     = freightInfo;
            receiveHeader.Notes           = notes;
            receiveHeader.Status          = "O";
            EntityHelper.SetAuditFields(id, receiveHeader, CurrentUserName);


            context.ReceivingDetails.DeleteAllOnSubmit(receiveHeader.ReceivingDetails);

            bool isFullReceived = true;

            foreach (var newReceivingDetail in detail)
            {
                var totalQtyPO  = orderDetails.Where(po => po.ItemID == newReceivingDetail.ItemID).Sum(po => po.Quantity);
                var totalQtyRcv = receivingDetails.Where(rcv => rcv.ItemID == newReceivingDetail.ItemID).Sum(rcv => rcv.QtyReceived);
                if (totalQtyPO - totalQtyRcv - newReceivingDetail.QtyReceived < 0)
                {
                    throw new Exception(String.Format("Qty for item {0} exceeds Qty in Purchase Order. Item:{1}, QtyPO:{2}, QtyRcv:{3}", newReceivingDetail.ItemCode, newReceivingDetail.ItemCode, Convert.ToInt32(totalQtyPO), totalQtyRcv + newReceivingDetail.QtyReceived));
                }
                else if (totalQtyPO - totalQtyRcv - newReceivingDetail.QtyReceived > 0)
                {
                    isFullReceived = false;
                }

                var receiveDetail = new ReceivingDetail
                {
                    ItemID          = newReceivingDetail.ItemID,
                    UnitName        = newReceivingDetail.UnitName,
                    QtyReceived     = newReceivingDetail.QtyReceived,
                    Notes           = newReceivingDetail.Notes,
                    ReceivingHeader = receiveHeader
                };
                context.ReceivingDetails.InsertOnSubmit(receiveDetail);
            }

            if (id == 0)
            {
                context.ReceivingHeaders.InsertOnSubmit(receiveHeader);
            }

            order.IsFullReceived  = isFullReceived;
            order.StatusReceiving = isFullReceived ? "F" : "P";


            //var receiveDetails = new List<ReceivingDetailViewModel>();
            //foreach (var item in query)
            //    receiveDetails.Add(new ReceivingDetailViewModel { ItemID = item.ItemID, QtyReceived = item.QtyReceived });

            //foreach (var lineDetail in detail)
            //    receiveDetails.Add(lineDetail);


            //var sumReceiveUnit = detail.GroupBy(x => x.ItemID).Select(y => new { item = y.Key, qty = receiveDetails.Where(x => x.ItemID == y.Key).Sum(x => x.QtyReceived) });


            //var sumPOUnit = context.PurchaseOrderHeaders.Where(x => x.ID == poID).SelectMany(x => x.PurchaseOrderDetails).
            //                                                GroupBy(x => x.ItemID).Select(z => new { item = z.Key, qty = z.Sum(p => p.Quantity) });

            //bool isAllqtySame = true;
            //bool isItemCountSame = true;

            //foreach (var itemReceive in sumReceiveUnit)
            //{
            //    var itemPO = sumPOUnit.SingleOrDefault(x => x.item == itemReceive.item);
            //    if (itemPO.qty != itemReceive.qty)
            //        isAllqtySame = false;
            //}

            //if (sumReceiveUnit.Count() != sumPOUnit.Count())
            //    isItemCountSame = false;

            //PurchaseOrderHeader purchaseOrderHeader = context.PurchaseOrderHeaders.SingleOrDefault(x => x.ID == poID);
            //if (purchaseOrderHeader != null)
            //{
            //    if (isAllqtySame && isItemCountSame)
            //    {
            //        var allReceiving = context.ReceivingHeaders.Where(x => x.PurchaseOrderID == poID && x.Status == "O");
            //        foreach (var item in allReceiving)
            //        {
            //            ReceivingHeader headerReceive = context.ReceivingHeaders.SingleOrDefault(x => x.ID == item.ID);
            //            headerReceive.Status = "F";
            //            EntityHelper.SetAuditFieldsForUpdate(headerReceive, CurrentUserName);
            //        }
            //        purchaseOrderHeader.IsFullReceived = true;
            //        purchaseOrderHeader.StatusReceiving = "F";
            //        receiveHeader.Status = "F";
            //        EntityHelper.SetAuditFieldsForUpdate(purchaseOrderHeader, CurrentUserName);
            //    }
            //    else
            //    {
            //        purchaseOrderHeader.IsFullReceived = false;
            //        purchaseOrderHeader.StatusReceiving = "P";
            //    }
            //}
            //#endregion

            context.SubmitChanges();

            return(receiveHeader.DocumentNo);
        }
		private object GetReferenceEntity(PXGraph graph, long? refNoteId)
		{
			if (refNoteId == null) return null;
			var helper = new EntityHelper(graph);
			return helper.GetEntityRow((long)refNoteId, true);
		}
Ejemplo n.º 32
0
        public void Find()
        {
            var person = EntityHelper.CreateProxy <Person>();

            person.Name       = "test";
            person.Age        = 20;
            person.Money      = 100;
            person.CreateTime = DateTime.Now;
            person.IsActive   = true;

            using (ISession session = SessionFactory.CreateDefaultSession())
            {
                session.Insert(person);

                int id = session.GetIndentifer <int>();

                var queryable = session.Find <Person>().Where(s => s.Id == id);

                // 测试 Single 函数
                person = queryable.Single();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                Assert.AreEqual("test", person.Name);
                Assert.AreEqual(20, person.Age.Value);
                Assert.AreEqual(100, person.Money.Value);
                Assert.AreEqual(true, person.IsActive);

                // 测试 SingleOrDefault 函数
                person = queryable.SingleOrDefault();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                Assert.AreEqual("test", person.Name);
                Assert.AreEqual(20, person.Age.Value);
                Assert.AreEqual(100, person.Money.Value);
                Assert.AreEqual(true, person.IsActive);

                // 测试 First 函数
                person = queryable.First();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                Assert.AreEqual("test", person.Name);
                Assert.AreEqual(20, person.Age.Value);
                Assert.AreEqual(100, person.Money.Value);
                Assert.AreEqual(true, person.IsActive);

                // 测试 FirstOrDefault 函数
                person = queryable.FirstOrDefault();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                Assert.AreEqual("test", person.Name);
                Assert.AreEqual(20, person.Age.Value);
                Assert.AreEqual(100, person.Money.Value);
                Assert.AreEqual(true, person.IsActive);

                // 测试 Count 函数
                Assert.AreEqual(1, queryable.Count());

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                // 测试 ToList 函数
                var list = queryable.ToList();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                Assert.AreEqual(1, list.Count());

                // 测试包含多个 Where 条件
                queryable = session.Find <Person>()
                            .Where(s => s.Id == id)
                            .Where(s => s.Name.Contains("test"))
                            .OrderBy(s => s.CreateTime)
                            .OrderBy(s => s.Name)
                            .Skip(0).Take(1);

                Assert.AreEqual(1, queryable.Count());

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);
            }
        }
Ejemplo n.º 33
0
        public void Update()
        {
            var person = EntityHelper.CreateProxy <Person>();

            person.Name       = "test";
            person.Age        = 20;
            person.Money      = 100;
            person.CreateTime = DateTime.Now;
            person.IsActive   = true;

            using (ISession session = SessionFactory.CreateDefaultSession())
            {
                int i = session.Insert(person);

                int id = session.GetIndentifer <int>();

                // Find 方法返回的对象都是原始对象而非代理对象
                person = session.Find <Person>().Where(s => s.Id == id).Single();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                // 根据原始对象创建代理对象
                person = person.ToEntityProxy();

                person.Name  = "test01";
                person.Age   = 31;
                person.Money = 200;

                i = session.Update(person);

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                person = session.Find <Person>().Where(s => s.Id == id).Single();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                Assert.AreEqual(1, i);
                Assert.AreEqual("test01", person.Name);
                Assert.AreEqual(31, person.Age.Value);
                Assert.AreEqual(200, person.Money.Value);

                person = EntityHelper.CreateProxy <Person>();

                person.Name       = "test02";
                person.Age        = 22;
                person.Money      = 101;
                person.CreateTime = DateTime.Now;
                person.IsActive   = false;

                i = session.Update <Person>()
                    .Set(person)
                    .Where(s => s.Id == id)
                    .Execute();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                person = session.Find <Person>().Where(s => s.Id == id).Single();

                Assert.AreEqual(1, i);
                Assert.AreEqual("test02", person.Name);
                Assert.AreEqual(22, person.Age.Value);
                Assert.AreEqual(101, person.Money.Value);
                Assert.AreEqual(false, person.IsActive);

                i = session.Update <Person>().Set(s => s.Name, "test03")
                    .Set(s => s.Age, 23)
                    .Set(s => s.Money, 102)
                    .Set(s => s.CreateTime, DateTime.Now)
                    .Set(s => s.IsActive, true)
                    .Where(s => s.Id == id)
                    .Execute();

                Console.WriteLine(session.Provider.ExecutedCommandBuilder);

                person = session.Find <Person>().Where(s => s.Id == id).Single();

                Assert.AreEqual(1, i);
                Assert.AreEqual("test03", person.Name);
                Assert.AreEqual(23, person.Age.Value);
                Assert.AreEqual(102, person.Money.Value);
                Assert.AreEqual(true, person.IsActive);
            }
        }
Ejemplo n.º 34
0
        protected void LoadData()
        {
            //clear
            ddCategory.Items.Clear();
            ddSection.Items.Clear();
            ddManufacturer.Items.Clear();
            ddDistributor.Items.Clear();

            //load Categories
            ddCategory.Items.Add(new ListItem(" - Select -", "-1"));
            EntityHelper eTemp = new EntityHelper(EntityDefinitions.readonly_CategoryEntitySpecs, 0);
            ArrayList    al    = eTemp.GetEntityArrayList(0, "", 0, LocaleSetting, false);

            for (int i = 0; i < al.Count; i++)
            {
                ListItemClass lic   = (ListItemClass)al[i];
                string        value = lic.Value.ToString();
                string        name  = Server.HtmlDecode(lic.Item);

                ddCategory.Items.Add(new ListItem(name, value));
            }

            //load Sections
            ddSection.Items.Add(new ListItem(" - Select -", "-1"));
            eTemp = new EntityHelper(EntityDefinitions.readonly_SectionEntitySpecs, 0);
            al    = eTemp.GetEntityArrayList(0, "", 0, LocaleSetting, false);
            for (int i = 0; i < al.Count; i++)
            {
                ListItemClass lic   = (ListItemClass)al[i];
                string        value = lic.Value.ToString();
                string        name  = Server.HtmlDecode(lic.Item);

                ddSection.Items.Add(new ListItem(name, value));
            }

            //load Manufacturers
            ddManufacturer.Items.Add(new ListItem(" - Select -", "-1"));
            eTemp = new EntityHelper(EntityDefinitions.readonly_ManufacturerEntitySpecs, 0);
            al    = eTemp.GetEntityArrayList(0, "", 0, LocaleSetting, false);
            for (int i = 0; i < al.Count; i++)
            {
                ListItemClass lic   = (ListItemClass)al[i];
                string        value = lic.Value.ToString();
                string        name  = Server.HtmlDecode(lic.Item);

                ddManufacturer.Items.Add(new ListItem(name, value));
            }

            //load Distributors
            ddDistributor.Items.Add(new ListItem(" - Select -", "-1"));

            using (var dbconn = new SqlConnection(DB.GetDBConn()))
            {
                dbconn.Open();
                using (var rsst = DB.GetRS("select * from Distributor   with (NOLOCK)  where Deleted=0 order by DisplayOrder,Name", dbconn))
                {
                    while (rsst.Read())
                    {
                        ddDistributor.Items.Add(new ListItem(DB.RSFieldByLocale(rsst, "Name", LocaleSetting), DB.RSFieldInt(rsst, "DistributorID").ToString()));
                    }
                }
            }
        }