Ejemplo n.º 1
0
        public int InsertLink(LinkInfo link)
        {
            string cmdText = @"insert into [loachs_links]
                            (
                            [type],[name],[href],[position],[target],[description],[displayorder],[status],[createdate]
                            )
                            values
                            (
                            @type,@name,@href,@position,@target,@description,@displayorder,@status,@createdate
                            )";
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@type",OleDbType.Integer,4,link.Type),
                                OleDbHelper.MakeInParam("@name",OleDbType.VarWChar,100,link.Name),
                                OleDbHelper.MakeInParam("@href",OleDbType.VarWChar,255,link.Href),
                                OleDbHelper.MakeInParam("@position",OleDbType.Integer,4,link.Position),
                                OleDbHelper.MakeInParam("@target",OleDbType.VarWChar,50,link.Target),
                                OleDbHelper.MakeInParam("@description",OleDbType.VarWChar,255,link.Description),
                                OleDbHelper.MakeInParam("@displayorder",OleDbType.Integer,4,link.Displayorder),
                                OleDbHelper.MakeInParam("@status",OleDbType.Integer,4,link.Status),
                                OleDbHelper.MakeInParam("@createdate",OleDbType.Date,8,link.CreateDate),
                            };

            int r = OleDbHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams);
            if (r > 0)
            {
                return Convert.ToInt32(OleDbHelper.ExecuteScalar("select top 1 [linkid] from [loachs_links]  order by [linkid] desc"));
            }
            return 0;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// insert link
        /// </summary>
        /// <param name="link"></param>
        /// <returns></returns>
        public int Insert(LinkInfo link)
        {
            string cmdText = string.Format(@"insert into [{0}links]
                            (
                            [type],[linkname],[linkurl],[position],[target],[description],[sortnum],[status],[createtime]
                            )
                            values
                            (
                            @type,@linkname,@linkurl,@position,@target,@description,@sortnum,@status,@createtime
                            )", ConfigHelper.Tableprefix);

            using (var conn = new DapperHelper().OpenConnection())
            {
                conn.Execute(cmdText, new
                {
                    Type = link.Type,
                    LinkName = link.LinkName,
                    LinkUrl = link.LinkUrl,
                    Postion = link.Position,
                    Target = link.Target,
                    Description = link.Description,
                    SortNum = link.SortNum,
                    Status = link.Status,
                    CreateTime = link.CreateTime
                });
                return conn.Query<int>(string.Format("select [linkid] from [{0}links]  order by [linkid] desc  limit 1", ConfigHelper.Tableprefix), null).First();
            }
        }
Ejemplo n.º 3
0
        public int UpdateLink(LinkInfo link)
        {
            string cmdText = string.Format(@"update [{0}links] set
                                [type]=@type,
                                [linkname]=@linkname,
                                [linkurl]=@linkurl,
                                [position]=@position,
                                [target]=@target,
                                [description]=@description,
                                [sortnum]=@sortnum,
                                [status]=@status,
                                [createtime]=@createtime
                                where linkid=@linkid",ConfigHelper.Tableprefix);
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@type",OleDbType.Integer,4,link.Type),
                                OleDbHelper.MakeInParam("@linkname",OleDbType.VarWChar,100,link.LinkName),
                                OleDbHelper.MakeInParam("@linkurl",OleDbType.VarWChar,255,link.LinkUrl),
                                OleDbHelper.MakeInParam("@position",OleDbType.Integer,4,link.Position),
                                OleDbHelper.MakeInParam("@target",OleDbType.VarWChar,50,link.Target),
                                OleDbHelper.MakeInParam("@description",OleDbType.VarWChar,255,link.Description),
                                OleDbHelper.MakeInParam("@sortnum",OleDbType.Integer,4,link.SortNum),
                                OleDbHelper.MakeInParam("@status",OleDbType.Integer,4,link.Status),
                                OleDbHelper.MakeInParam("@createtime",OleDbType.Date,8,link.CreateTime),
                                OleDbHelper.MakeInParam("@linkid",OleDbType.Integer,4,link.LinkId),
                            };

            return Convert.ToInt32(OleDbHelper.ExecuteScalar(CommandType.Text, cmdText, prams));
        }
Ejemplo n.º 4
0
        public LinkInfo SetUpContext(PanelPreferences preferences, string skinFolderPath)
        {
            // Offline and Advanced mode Changes

            var linkInfo = new LinkInfo {FolderName = Res.FolderName};
            if (!preferences.OfflineMode)
            {
                CookieJar = Login(preferences);

                CookieJar = Home.HomeViewPostToPanelSettingsManager(CookieJar, preferences);  //Source code here contains the Panel Settings Form

                var collection = new ContextCollection(CookieJar.SourceCode);

                ContextInfo contextInfo = collection.FindAvailableContext();
                Environment = contextInfo.Environment;

                collection.UpdateFormValue(contextInfo.ContextIndex, -1, "OpenPortalSkinFolder", contextInfo.SubDomain);
                collection.UpdateFormValue(contextInfo.ContextIndex, -1, "PortalSkinPath", Res.PortalSkinPathParent + "/" + contextInfo.SubDomain + "/");
                collection.UpdateFormValue(contextInfo.ContextIndex, -1, "IsHidden", "False");
                collection.UpdateFormValue(contextInfo.ContextIndex, -1, "Name", preferences.CompanyName + " Portal");
                // Added for Language selection
                collection.UpdateFormValue(contextInfo.ContextIndex, -1, "Culture", preferences.Language);

                PanelSettingsManagement.PanelSettingsUpdatePost(CookieJar, collection, preferences);
                linkInfo.FolderName = contextInfo.SubDomain;
                linkInfo.PortalLink = contextInfo.OpenPortalTestBaseUrl; //TODO CHANGE TO LIVE LINK
            }
            return linkInfo;
        }
Ejemplo n.º 5
0
        public int InsertLink(LinkInfo link)
        {
            string cmdText = string.Format(@"insert into [{0}links]
                            (
                            [type],[linkname],[linkurl],[position],[target],[description],[sortnum],[status],[createtime]
                            )
                            values
                            (
                            @type,@linkname,@linkurl,@position,@target,@description,@sortnum,@status,@createtime
                            )",ConfigHelper.Tableprefix);
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@type",OleDbType.Integer,4,link.Type),
                                OleDbHelper.MakeInParam("@linkname",OleDbType.VarWChar,100,link.LinkName),
                                OleDbHelper.MakeInParam("@linkurl",OleDbType.VarWChar,255,link.LinkUrl),
                                OleDbHelper.MakeInParam("@position",OleDbType.Integer,4,link.Position),
                                OleDbHelper.MakeInParam("@target",OleDbType.VarWChar,50,link.Target),
                                OleDbHelper.MakeInParam("@description",OleDbType.VarWChar,255,link.Description),
                                OleDbHelper.MakeInParam("@sortnum",OleDbType.Integer,4,link.SortNum),
                                OleDbHelper.MakeInParam("@status",OleDbType.Integer,4,link.Status),
                                OleDbHelper.MakeInParam("@createtime",OleDbType.Date,8,link.CreateTime),
                            };

            int r = OleDbHelper.ExecuteNonQuery(CommandType.Text, cmdText, prams);
            if (r > 0)
            {
                return Convert.ToInt32(OleDbHelper.ExecuteScalar(string.Format("select top 1 [linkid] from [{0}links]  order by [linkid] desc",ConfigHelper.Tableprefix)));
            }
            return 0;
        }
Ejemplo n.º 6
0
 /// <summary>
 /// delete link
 /// </summary>
 /// <param name="link"></param>
 /// <returns></returns>
 public int Delete(LinkInfo link)
 {
     string cmdText = string.Format("delete from [{0}links] where [linkid] = @linkid", ConfigHelper.Tableprefix);
     using (var conn = new DapperHelper().OpenConnection())
     {
         return conn.Execute(cmdText, new { categoryid = link.LinkId });
     }
 }
Ejemplo n.º 7
0
 public static LinkInfo Link(ITransformable parent, ITransformable child, Vector3 offset, Quaternion Rotation)
 {
     var link = new LinkInfo()
     {
         Parent = parent,
         Child = child,
         Offset = offset,
         Rotation = Rotation
     };
     Links.Add(link);
     return link;
 }
Ejemplo n.º 8
0
        public ActionResult VoteLinkSg(string id, string message, bool? confirm)
        {
            var li = new LinkInfo(votelinkSTR, landingSTR, id);
            if (li.error.HasValue())
                return Message(li.error);

            ViewBag.Id = id;
            ViewBag.Message = message;
            ViewBag.Confirm = confirm.GetValueOrDefault().ToString();

            var smallgroup = li.a[4];
            DbUtil.LogActivity($"{votelinkSTR}{landingSTR}: {smallgroup}", li.oid, li.pid);
            return View("Other/VoteLinkSg");
        }
Ejemplo n.º 9
0
        public LinkInfo SetUpContext(PanelPreferences preferences, string skinFolderPath)
        {
            // Offline and Advanced mode Changes by Optimus

            var linkInfo = new LinkInfo {FolderName = Res.FolderName};
            if (!preferences.OfflineMode)
            {
                CookieJar = Login(preferences);

                try
                {
                    CookieJar = Home.HomeViewPostToPanelSettingsManager(CookieJar, preferences);  //Source code here contains the Panel Settings Form

                    if (CookieJar.SourceCode.IndexOf("Settings are locked by VcAdmin") > 0)
                    {
                        throw new Exception("Settings are currently locked, navigate away from settings, recycle or wait");
                    }
                    var collection = new ContextCollection(CookieJar.SourceCode);

                    ContextInfo contextInfo = collection.FindAvailableContext();
                    Environment = contextInfo.Environment;

                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "OpenPortalSkinFolder", contextInfo.FolderName());
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "PortalSkinPath", Res.PortalSkinPathParent + "/" + contextInfo.FolderName() + "/");
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "IsHidden", "False");
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "Name", preferences.CompanyName + " Portal");

                    // Added for Language selection by Optimus
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "Culture", preferences.Language);

                    PanelSettingsManagement.PanelSettingsUpdatePost(CookieJar, collection, preferences);
                    linkInfo.FolderName = contextInfo.FolderName();
                    linkInfo.PortalLink = contextInfo.OpenPortalTestBaseUrl; //TODO CHANGE TO LIVE LINK
                }
                catch (Exception e)
                {
                    // attempt to Navigate away to attempt not to lock panel settings
                    try
                    {
                        PanelSettingsManagement.PanelSettingsPostToAssetManager(CookieJar, preferences);
                    }
                    catch (Exception) { }
                    throw e;
                }
            }
            return linkInfo;
        }
Ejemplo n.º 10
0
        public LinkInfo Build(string schema, string name, Tuple<string, string> anchorId, Tuple<string, string> infoId, Tuple<string, string> dateId, IEnumerable<Tuple<string, string>> filters)
        {
            var tableName = new ObjectIdentifier(new string[] { schema, name });
            var foreignKeyColumns = new List<TSqlColumn>();

            var sqlDataTypeFactory = new TSqlDataTypeFactory();
            var sqlDataType = sqlDataTypeFactory.Build(anchorId.Item2);

            var columnFactory = new ColumnFactory();
            var anchorKey = columnFactory.Build(anchorId.Item1, sqlDataType);
            foreignKeyColumns.Add(anchorKey);

            sqlDataType = sqlDataTypeFactory.Build(infoId.Item2);
            var infoKey = columnFactory.Build(infoId.Item1, sqlDataType);
            foreignKeyColumns.Add(infoKey);

            sqlDataType = sqlDataTypeFactory.Build(dateId.Item2);
            var dateKey = columnFactory.Build(dateId.Item1, sqlDataType);
            foreignKeyColumns.Add(dateKey);

            var uniqueKeyColumns = new TSqlColumnList();
            uniqueKeyColumns.Add(anchorKey);
            uniqueKeyColumns.Add(dateKey);

            var filterColumns = new List<TSqlColumn>();
            foreach (var filter in filters)
            {
                sqlDataType = sqlDataTypeFactory.Build(filter.Item2);
                var column = columnFactory.Build(filter.Item1, sqlDataType);
                filterColumns.Add(column);
            }

            var link = new LinkInfo()
            {
                Name = tableName,
                UniqueKey = uniqueKeyColumns,
                DateKey = dateKey,
                AnchorKey = anchorKey,
                InfoKey = infoKey,
                ForeignKeys = foreignKeyColumns,
                Filters = filterColumns
            };
            return link;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            LinkInfo link = new LinkInfo();
            if (Operate == OperateType.Update)
            {
                link = LinkManager.GetLink(linkId);
            }
            else
            {
                link.CreateDate = DateTime.Now;
                link.Type = 0;// (int)LinkType.Custom;
            }
            link.Name = StringHelper.HtmlEncode(txtName.Text.Trim());
            link.Href = StringHelper.HtmlEncode(txtHref.Text.Trim());
            link.Description = StringHelper.HtmlEncode(txtDescription.Text);
            link.Displayorder = StringHelper.StrToInt(txtDisplayOrder.Text, 1000);
            link.Status = chkStatus.Checked ? 1 : 0;
            link.Position = chkPosition.Checked ? (int)LinkPosition.Navigation : (int)LinkPosition.General;
            link.Target = chkTarget.Checked ? "_blank" : "_self";

            if (link.Name == "")
            {
                ShowError("请输入名称!");
                return;
            }

            if (Operate == OperateType.Update)
            {
                LinkManager.UpdateLink(link);

                Response.Redirect("linklist.aspx?result=2");
            }
            else
            {
                LinkManager.InsertLink(link);
                Response.Redirect("linklist.aspx?result=1");
            }
        }
        /// <summary>
        /// Adds the link to table information link definition.
        /// </summary>
        /// <param name="tableInfo">
        /// The table information.
        /// </param>
        /// <param name="linkDefArray">
        /// The link definition array.
        /// </param>
        private void AddLink(TableInfo tableInfo, JArray linkDefArray)
        {
            var sourceFieldId = -1;
            var destFieldId   = -1;
            int linkFlag;

            if (linkDefArray.Count > 4)
            {
                sourceFieldId = JObjectExtensions.ToInt(linkDefArray[4]);
                destFieldId   = JObjectExtensions.ToInt(linkDefArray[5]);
            }
            else
            {
                sourceFieldId = -1;
                destFieldId   = -1;
            }

            if (linkDefArray.Count > 7)
            {
                linkFlag = JObjectExtensions.ToInt(linkDefArray[7]);
            }
            else
            {
                linkFlag = 0;
            }

            var arr = linkDefArray.Count > 6 ? linkDefArray[6] as JArray : null;

            if (arr == null)
            {
                return;
            }

            var linkFieldCount          = arr.Count;
            var sourceFieldIds          = new int[linkFieldCount];
            var destinationFieldIds     = new int[linkFieldCount];
            var sourceValuesBuffer      = new string[linkFieldCount];
            var destinationValuesBuffer = new string[linkFieldCount];

            for (var i = 0; i < arr.Count; i++)
            {
                var fieldArray = arr[i] as JArray;
                sourceFieldIds[i]      = JObjectExtensions.ToInt(fieldArray?[0]);
                destinationFieldIds[i] = JObjectExtensions.ToInt(fieldArray?[1]);
                if (fieldArray.Count > 2)
                {
                    var sourceValue = fieldArray[2];
                    var destValue   = fieldArray[3];

                    sourceValuesBuffer[i]      = (string)sourceValue;
                    destinationValuesBuffer[i] = (string)destValue;
                }
                else
                {
                    sourceValuesBuffer[i]      = null;
                    destinationValuesBuffer[i] = null;
                }
            }

            var linkInfo = new LinkInfo(
                tableInfo.InfoAreaId,
                (string)linkDefArray[0],
                JObjectExtensions.ToInt(linkDefArray[1]),
                JObjectExtensions.ToInt(linkDefArray[2]),
                LinkInfo.ToLinkType((string)linkDefArray[3]),
                sourceFieldId,
                destFieldId,
                linkFieldCount,
                sourceFieldIds,
                destinationFieldIds,
                linkFlag,
                sourceValuesBuffer,
                destinationValuesBuffer);

            tableInfo.AddLinkInfoWithOwnership(linkInfo);
        }
Ejemplo n.º 13
0
        public static string PreViewComment(string content)
        {
            try
            {
                if (StringHlp.IsEmpty(content))
                {
                    return("");
                }

                LinkInfo[] links = GetLinks(content);
                if (links.Length > 0)
                {
                    StringBuilder builder = new StringBuilder();
                    if (links[0].Index > 0)
                    {
                        builder.Append(content.Substring(0, links[0].Index));
                    }

                    for (int i = 0; i < links.Length; ++i)
                    {
                        LinkInfo link = links[i];
                        if (!link.IsImage)
                        {
                            string display = link.Value;
                            if (display.StartsWith(httpPrefix))
                            {
                                display = display.Substring(httpPrefix.Length);
                            }
                            else if (display.StartsWith(httpsPrefix))
                            {
                                display = display.Substring(httpsPrefix.Length);
                            }

                            if (display.Length > 50)
                            {
                                display = display.Substring(0, 50);
                            }

                            builder.AppendFormat(linkFormat, link.Value, display);
                        }
                        else
                        {
                            builder.AppendFormat(imageFormat, link.Value);
                        }

                        int startIndex = link.Index + link.Value.Length;
                        int endIndex   = content.Length;
                        if (i + 1 < links.Length)
                        {
                            endIndex = links[i + 1].Index;
                        }

                        if (endIndex > startIndex)
                        {
                            builder.Append(content.Substring(startIndex, endIndex - startIndex));
                        }
                    }

                    content = builder.ToString();
                }

                content = content.Replace("\n", "<br>");

                content = content.Replace(":)", Smiley.Smile);
                content = content.Replace(":(", Smiley.Sad);
                content = content.Replace(" :/", Smiley.Blah);
                content = content.Replace(" ;)", Smiley.Wink);


                return(content);
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                return(content);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="link"></param>
        /// <returns></returns>
        public static int InsertLink(LinkInfo link)
        {
            link.LinkId = dao.InsertLink(link);
            _links.Add(link);
            _links.Sort();

            return link.LinkId;
        }
Ejemplo n.º 15
0
    // такая же катушка, только для В
    void coilBCheck()
    {
        //если скорость нулевая, то нет смысла что-то там сложно просчитывать
        if (coilBSpeed == 0 || prefabsList.Count == 0 || B == null)
        {
            return;
        }


        // ОТМОТКА от B
        float coilВSpeedReduсer = coilBSpeed * 0.01f; // чтобы скорость в инспекторе не выставлялась такой большой, работаю с уменьшеной копией оригинальной скорости.

        if (coilВSpeedReduсer > 0)                    //нужно двигать от B
        {
            //если отматывать нечего, или последнее звено не присоеденено к В - то создаём новое звено и завершаем метод
            if (links.Count == 0 || links[links.Count - 1].hingle2_IsExistActiveAndConnectedTo(B.GetComponent <Rigidbody2D>()) == false)
            {
                if (chainMode == ChainMode.None)
                {
                    currentId = prefabId;
                }
                else if (chainMode == ChainMode.Random)
                {
                    currentId = links.Count == 0 ? UnityEngine.Random.Range(0, prefabsList.Count) : links[links.Count - 1].prefabIdNext;
                }
                else if (chainMode == ChainMode.Queue)
                {
                    currentId = (links.Count + queueOffset) % prefabsList.Count;
                }
                addPartFromB(currentId);
                return;
            }

            LinkInfo lastPart = links[links.Count - 1];


            //направление от B до правой стороны последнего звена (тащим ведь за правую сторону)
            Vector3 dir = lastPart.obj.transform.TransformPoint(Vector3.right * lastPart.widthHalf) - B.transform.TransformPoint(offsetB);

            //Vector3 dir = lastPart.hingleJoint_2.connectedAnchor - offsetB;
            float dist = dir.magnitude;
            dist += coilВSpeedReduсer;


            //если звено одно, то тащить его вниз от B, иначе тащить в сторону к предыдущему звену, если текущее звено привязано к нему
            if (links.Count > 1 && lastPart.hingle1_IsActiveAndConnectedTo(links[links.Count - 2].rb2D))
            {
                lastPart.hingleJoint_2.connectedAnchor += (Vector2)(B.transform.InverseTransformDirection(links[links.Count - 2].obj.transform.position - lastPart.obj.transform.position).normalized) * coilВSpeedReduсer;
            }
            else
            {
                lastPart.hingleJoint_2.connectedAnchor = (Vector3)offsetB + (Vector3.down * dist);
            }


            float w = (_prefabsListWidths[lastPart.prefabIdNext] + anchorOffset) * scaleFactorX;

            // СОЗДАТЬ ЛИ НОВОЕ? Если звено дальше от А, чем ширина нового звена (которое появится), то создать новое звено
            if (dist >= w)
            {
                //создать новое звено и прецепить к А серединой
                addPartFromB(lastPart.prefabIdNext);
            }
        }
        // НАМОТКА на В
        else if (coilВSpeedReduсer < 0)
        {
            // если звеньев нет, или последнее звено не привязано к В, то тащить нечего..
            if (links.Count == 0 || links[links.Count - 1].hingle2_IsExistActiveAndConnectedTo(B.GetComponent <Rigidbody2D>()) == false)
            {
                return;
            }

            LinkInfo lastPart = links[links.Count - 1];
            //расстояние и направление от В, до крепления последнего звена
            Vector3 dir  = lastPart.hingleJoint_2.connectedAnchor - offsetB;
            float   dist = dir.magnitude;

            //уменьшить расстояние, но не на больше, чем само расстояние
            dist += coilВSpeedReduсer > dist ? dist : coilВSpeedReduсer;

            // уменьшить расстояние от последнего звена до В
            lastPart.hingleJoint_2.connectedAnchor = (Vector3)offsetB + (dir.normalized * dist);

            if (dist <= 0.01f)
            {
                // если звеньев было несколько и то, которое тащили было привязано к другому
                if (links.Count > 1 && lastPart.hingle1_IsActiveAndConnectedTo(links[links.Count - 2].rb2D))
                {
                    //предпоследнее звено
                    LinkInfo penultimatePart = links[links.Count - 2];

                    // прицепить педпоследнее звено к В вторым джоинтом.
                    if (penultimatePart.hingleJoint_2 == null)
                    {
                        penultimatePart.hingleJoint_2 = penultimatePart.obj.AddComponent <HingeJoint2D>();
                    }


                    //прицепить предпоследнее звено вторым джоинтом к В, на текущем расстоянии
                    penultimatePart.hingleJoint_2.connectedBody = B.GetComponent <Rigidbody2D>();

                    penultimatePart.hingleJoint_2.connectedAnchor = B.transform.InverseTransformPoint(penultimatePart.obj.transform.TransformPoint(Vector3.right * penultimatePart.widthHalf));

                    penultimatePart.hingleJoint_2.anchor = Vector3.right * penultimatePart.widthHalf;
                }

                Destroy(lastPart.obj);
                links.RemoveAt(links.Count - 1);
            }
        }
    }
Ejemplo n.º 16
0
        public ActionResult VoteLinkSg(string id, string message, bool? confirm, FormCollection formCollection)
        {
            var li = new LinkInfo(votelinkSTR, confirmSTR, id);
            if (li.error.HasValue())
                return Message(li.error);

            try
            {
                var smallgroup = li.a[4];

                if (!li.oid.HasValue)
                    throw new Exception("orgid missing");

                if (!li.pid.HasValue)
                    throw new Exception("peopleid missing");

                var q = (from pp in DbUtil.Db.People
                         where pp.PeopleId == li.pid
                         let org = DbUtil.Db.Organizations.SingleOrDefault(oo => oo.OrganizationId == li.oid)
                         let om = DbUtil.Db.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == li.oid && oo.PeopleId == li.pid)
                         select new {p = pp, org, om}).Single();

                if (q.org == null && DbUtil.Db.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in DbUtil.Db.People
                         where pp.PeopleId == li.pid
                         let org = DbUtil.Db.Organizations.SingleOrDefault(oo => oo.OrganizationId == oid)
                         let om = DbUtil.Db.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == oid && oo.PeopleId == li.pid)
                         select new {p = pp, org, om}).Single();
                }

                if (q.org == null)
                {
                    throw new Exception("org missing, bad link");
                }
                if ((q.org.RegistrationTypeId ?? RegistrationTypeCode.None) == RegistrationTypeCode.None)
                    throw new Exception("votelink is no longer active");

                if (q.om == null && q.org.Limit <= q.org.RegLimitCount(DbUtil.Db))
                    throw new Exception("sorry, maximum limit has been reached");

                if (q.om == null &&
                    (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive))
                    throw new Exception("sorry, registration has been closed");

                var setting = DbUtil.Db.CreateRegistrationSettings(li.oid.Value);
                if (IsSmallGroupFilled(setting, li.oid.Value, smallgroup))
                    throw new Exception("sorry, maximum limit has been reached for " + smallgroup);

                var omb = OrganizationMember.InsertOrgMembers(DbUtil.Db,
                    li.oid.Value, li.pid.Value, MemberTypeCode.Member, DateTime.Now, null, false);

                if (q.org.AddToSmallGroupScript.HasValue())
                {
                    var script = DbUtil.Db.Content(q.org.AddToSmallGroupScript);
                    if (script != null && script.Body.HasValue())
                    {
                        try
                        {
                            var pe = new PythonEvents(Util.Host, "RegisterEvent", script.Body);
                            pe.instance.AddToSmallGroup(smallgroup, omb);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                omb.AddToGroup(DbUtil.Db, smallgroup);
                li.ot.Used = true;
                DbUtil.Db.SubmitChanges();

                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}: {smallgroup}", li.oid, li.pid);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(DbUtil.Db, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", smallgroup);
                    var NotifyIds = DbUtil.Db.StaffPeopleForOrg(q.org.OrganizationId);

                    try
                    {
                        DbUtil.Db.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    }
                    catch (Exception ex)
                    {
                        DbUtil.Db.Email(q.p.FromEmail, NotifyIds,
                            q.org.OrganizationName,
                            "There was a problem sending confirmation from org: " + ex.Message);
                    }
                    DbUtil.Db.Email(q.p.FromEmail, NotifyIds,
                        q.org.OrganizationName,
                        $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{smallgroup}<br>(from votelink)");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return Message(ex.Message);
            }

            return Message(message);
        }
Ejemplo n.º 17
0
 public static void Unlink(LinkInfo info)
 {
     Links.Remove(info);
 }
Ejemplo n.º 18
0
 private void WeightValueLinkHandle_OnAddLinkInfo(LinkInfo linkInfo)
 {
     WeightValueTextBlock.Visibility = Visibility.Collapsed;
 }
Ejemplo n.º 19
0
        public ActionResult RsvpLinkSg(string id, string message, bool? confirm, bool regrets = false)
        {
            var li = new LinkInfo(rsvplinkSTR, landingSTR, id, false);
            if (li.error.HasValue())
                return Message(li.error);

            ViewBag.Id = id;
            ViewBag.Message = message;
            ViewBag.Confirm = confirm.GetValueOrDefault().ToString();
            ViewBag.Regrets = regrets.ToString();

            DbUtil.LogActivity($"{rsvplinkSTR}{landingSTR}: {regrets}", li.oid, li.pid);
            return View("Other/RsvpLinkSg");
        }
Ejemplo n.º 20
0
 private void AlphaValueLinkHandle_OnDelLinkInfo(LinkInfo linkInfo)
 {
     AlphaValueTextBlock.Visibility = Visibility.Visible;
 }
Ejemplo n.º 21
0
 private void WeightValueLinkHandle_OnDelLinkInfo(LinkInfo linkInfo)
 {
     WeightValueTextBlock.Visibility = Visibility.Visible;
 }
Ejemplo n.º 22
0
 public ContextData Reset()
 {
     link  = null;
     chirp = null;
     return(ContextData.Empty);
 }
Ejemplo n.º 23
0
 public void SetLink(string type, string url)
 {
     link = string.IsNullOrEmpty(url) ? null : new LinkInfo(type, url);
 }
Ejemplo n.º 24
0
 /// <summary>
 /// 修改
 /// </summary>
 /// <param name="link"></param>
 /// <returns></returns>
 public static int UpdateLink(LinkInfo link)
 {
     _links.Sort();
     return dao.UpdateLink(link);
 }
Ejemplo n.º 25
0
 internal S3Link(S3ClientCache clientCache, string json)
 {
     if (clientCache == null) throw new ArgumentNullException("clientCache");
     if (json == null) throw new ArgumentNullException("json");
     this.s3ClientCache = clientCache;
     linker = JsonMapper.ToObject<LinkInfo>(json);
 }
Ejemplo n.º 26
0
    protected void populateMaps(NodeLinkDataLoader dataLoader)
    {
        nodeMap  = new Dictionary <string, NodeInfo>();
        linkList = new List <LinkInfo>();
        groupMap = new Dictionary <string, List <NodeInfo> >();

        Color[] palette = ColorUtils.getColorPalette();
        ColorUtils.randomizeColorPalette(palette);

        Dictionary <int, int> colorSet = new Dictionary <int, int>();
        int currGroup;

        NodeInfo        currNode;
        List <NodeInfo> currGrpList;

        foreach (NLNode node in dataLoader.nodes)
        {
            currNode         = new NodeInfo();
            currNode.id      = node.id;
            currNode.group   = node.group;
            currNode.groupId = node.groupId;
            currNode.color   = palette[currNode.group % palette.Length];

            nodeMap.Add(node.id, currNode);

            if (!groupMap.TryGetValue(currNode.groupId, out currGrpList))
            {
                currGrpList = new List <NodeInfo>();
                groupMap.Add(currNode.groupId, currGrpList);
            }

            currGrpList.Add(currNode);

            if (!colorSet.TryGetValue(currNode.group, out currGroup))
            {
                colorSet.Add(currNode.group, 0);
            }
        }

        foreach (NLCoord coord in dataLoader.coords)
        {
            if (nodeMap.TryGetValue(coord.id, out currNode))
            {
                currNode.pos2d = new Vector2(coord.x, coord.y);
            }
        }

        NodeInfo startNode;
        NodeInfo endNode;
        LinkInfo currLink;



        Random.InitState(97);

        foreach (NLLink link in dataLoader.links)
        {
            if (nodeMap.TryGetValue(link.source, out startNode) &&
                nodeMap.TryGetValue(link.target, out endNode))
            {
                currLink            = new LinkInfo();
                currLink.start      = startNode;
                currLink.end        = endNode;
                currLink.lineWidth  = link.lineWidth;
                currLink.forceValue = Mathf.Sqrt((float)link.value) + Random.value * 0.5f;
                linkList.Add(currLink);
            }
        }
    }
Ejemplo n.º 27
0
 /// <summary>
 /// 添加
 /// </summary>
 /// <param name="link"></param>
 /// <returns></returns>
 public int InsertLink(LinkInfo link)
 {
     link.LinkId =  _linkRepository.Insert(link);
     return link.LinkId;
 }
        /// <summary>
        /// Creates the record.
        /// </summary>
        /// <param name="record">The record.</param>
        /// <param name="undo">if set to <c>true</c> [undo].</param>
        /// <returns>Record</returns>
        public DAL.Record CreateRecord(UPCRMRecord record, bool undo)
        {
            string             infoAreaId = record.InfoAreaId;
            List <FieldIdType> fieldIds;
            List <string>      linkFieldNames;
            bool checkDataModel = true;

            TableInfo tableInfo = this.DatabaseInstance.GetTableInfoByInfoArea(infoAreaId);

            if (tableInfo == null)
            {
                return(null);
            }

            int  statNoField = 0, lnrField = 0;
            bool saveOfflineStationNumber = false;

            if (!undo && record.OfflineRecordNumber > 0 && record.OfflineStationNumber > 0)
            {
                statNoField = tableInfo.GetStatNoFieldId();
                if (statNoField >= 0)
                {
                    lnrField = tableInfo.GetLNrFieldId();
                    if (lnrField >= 0 && tableInfo.GetFieldInfo(statNoField) != null && tableInfo.GetFieldInfo(lnrField) != null)
                    {
                        saveOfflineStationNumber = true;
                    }
                }
            }

            List <UPCRMFieldValue> fieldValues = record.FieldValues;
            int fieldCount = fieldValues?.Count ?? 0;
            int linkCount  = record.Links?.Count ?? 0;

            if (undo)
            {
                linkCount = 0;
            }

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

            if (fieldCount == 0)
            {
                fieldIds = null;
            }
            else
            {
                fieldIds = new List <FieldIdType>();
                for (int i = 0; i < fieldCount; i++)
                {
                    UPCRMFieldValue fieldValue = fieldValues[i];
                    FieldInfo       fieldInfo  = tableInfo.GetFieldInfo(fieldValue.FieldId);
                    if (!checkDataModel || fieldInfo != null)
                    {
                        int currentFieldId = fieldValue.FieldId;
                        fieldIds.Add((FieldIdType)currentFieldId);
                        recordFieldValues.Add(undo ? fieldValue.OldValue : fieldValue.Value);

                        if (saveOfflineStationNumber && (currentFieldId == statNoField || currentFieldId == lnrField))
                        {
                            saveOfflineStationNumber = false;
                        }
                    }
                }

                if (saveOfflineStationNumber)
                {
                    fieldIds.Add((FieldIdType)statNoField);
                    recordFieldValues.Add(record.OfflineStationNumber.ToString());
                    fieldIds.Add((FieldIdType)lnrField);
                    recordFieldValues.Add(record.OfflineRecordNumber.ToString());
                }
            }

            if (record.Links != null && (record.Links.Count == 0 || undo))
            {
                linkFieldNames = null;
                linkCount      = 0;
            }
            else
            {
                linkFieldNames = new List <string>();
                for (int i = 0; i < linkCount; i++)
                {
                    UPCRMLink link     = record.Links[i];
                    LinkInfo  linkInfo = tableInfo.GetLink(link.LinkFieldName()) ??
                                         tableInfo.GetLink(link.InfoAreaId, link.LinkId);

                    if (linkInfo != null && linkInfo.HasColumn)
                    {
                        if (linkInfo.IsGeneric)
                        {
                            string targetInfoAreaId = this.RootPhysicalInfoAreaIdForInfoAreaId(link.InfoAreaId);
                            recordFieldValues.Add(targetInfoAreaId);
                            linkFieldNames.Add(linkInfo.InfoAreaColumnName);
                        }

                        recordFieldValues.Add(link.RecordId);
                        linkFieldNames.Add(linkInfo.ColumnName);
                    }
                }
            }

            var recordTemplate = new RecordTemplate(
                this.DatabaseInstance,
                false,
                infoAreaId,
                fieldIds?.Count ?? 0,
                fieldIds?.ToArray(),
                linkFieldNames.Count,
                linkFieldNames,
                false,
                false);

            Record rec = new Record(infoAreaId, record.RecordId);

            rec.SetTemplate(recordTemplate);
            for (var i = 0; i < recordFieldValues.Count; i++)
            {
                rec.SetValue(i, recordFieldValues[i]);
            }

            return(rec);
        }
Ejemplo n.º 29
0
        public ActionResult SendLink(string id)
        {
            var li = new LinkInfo(sendlinkSTR, landingSTR, id);
            if (li.error.HasValue())
                return Message(li.error);

            ViewBag.Id = id;
            DbUtil.LogActivity($"{sendlinkSTR}{landingSTR}", li.oid, li.pid);
            return View("Other/SendLink");
        }
Ejemplo n.º 30
0
        public int UpdateLink(LinkInfo link)
        {
            string cmdText = @"update [loachs_links] set
                                [type]=@type,
                                [name]=@name,
                                [href]=@href,
                                [position]=@position,
                                [target]=@target,
                                [description]=@description,
                                [displayorder]=@displayorder,
                                [status]=@status,
                                [createdate]=@createdate
                                where linkid=@linkid";
            OleDbParameter[] prams = {
                                OleDbHelper.MakeInParam("@type",OleDbType.Integer,4,link.Type),
                                OleDbHelper.MakeInParam("@name",OleDbType.VarWChar,100,link.Name),
                                OleDbHelper.MakeInParam("@href",OleDbType.VarWChar,255,link.Href),
                                OleDbHelper.MakeInParam("@position",OleDbType.Integer,4,link.Position),
                                OleDbHelper.MakeInParam("@target",OleDbType.VarWChar,50,link.Target),
                                OleDbHelper.MakeInParam("@description",OleDbType.VarWChar,255,link.Description),
                                OleDbHelper.MakeInParam("@displayorder",OleDbType.Integer,4,link.Displayorder),
                                OleDbHelper.MakeInParam("@status",OleDbType.Integer,4,link.Status),
                                OleDbHelper.MakeInParam("@createdate",OleDbType.Date,8,link.CreateDate),
                                OleDbHelper.MakeInParam("@linkid",OleDbType.Integer,4,link.LinkId),
                            };

            return Convert.ToInt32(OleDbHelper.ExecuteScalar(CommandType.Text, cmdText, prams));
        }
        private void LoadLinkInfo()
        {
            XmlElement linkroot = _config["Link"];
            if (linkroot != null)
            {
                XmlElement namenode = linkroot["Name"];
                XmlElement linknode = linkroot["URL"];
                XmlElement onmenunode = linkroot["OnMenu"];
                if (namenode != null && linknode != null && onmenunode != null)
                {
                    string name = namenode.InnerText;
                    string url = linknode.InnerText;
                    bool onmenu;
                    if (!bool.TryParse(onmenunode.InnerText, out onmenu))
                        onmenu = false;

                    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(url))
                        _linkinfo = new LinkInfo(name, url, onmenu);
                }
            }
        }
Ejemplo n.º 32
0
        private string GetLink(LinkInfo info)
        {
            if (SelectedSeasonType != null)
            {
                info.seasonType = info.seasonType ?? SelectedSeasonType.Id;
            }
            else
            {
                info.seasonType = info.seasonType ?? _database.SeasonTypes.First().Id;
            }

            if (SelectedSeason != null)
            {
                info.seasonNum = info.seasonNum ?? SelectedSeason.Number;
            }
            if (info.seasonNum == 0)
            {
                info.seasonNum = null;
            }

            if (SelectedTeam != null)
            {
                info.teamId = info.teamId ?? SelectedTeam.Id;
            }
            if (info.teamId == 0)
            {
                info.teamId = null;
            }

            if (SelectedColumnSort != null)
            {
                info.sortOrder = info.sortOrder ?? SelectedColumnSort;
            }

            if (SelectedLeagueEra != null)
            {
                info.era = info.era ?? SelectedLeagueEra;
            }
            if (info.era == 0)
            {
                info.era = null;
            }

            if (info.playerType != null)
            {
                info.sortDesc  = true;
                info.sortOrder = null;
                info.pageNum   = null;
            }
            else
            {
                info.playerType = PageName;
            }

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

            if (info.leagueId != null)
            {
                parameters.Add($"li={info.leagueId}");
            }
            else
            {
                if (info.seasonNum != null)
                {
                    parameters.Add($"sn={info.seasonNum}");
                }
                if (info.seasonType != null)
                {
                    parameters.Add($"st={info.seasonType}");
                }
                if (info.teamId != null)
                {
                    parameters.Add($"ti={info.teamId}");
                }
                if (info.era != null)
                {
                    parameters.Add($"era={info.era}");
                }
                if (info.pageNum != null)
                {
                    parameters.Add($"pn={info.pageNum}");
                }
                if (info.sortOrder != null)
                {
                    parameters.Add($"so={info.sortOrder}");
                }
                if (info.sortDesc == false)
                {
                    parameters.Add($"sd=1");
                }
            }

            return($"{info.playerType}?{string.Join("&", parameters)}");
        }
Ejemplo n.º 33
0
    public void ReceiveWeb(string json)
    {
        Debug.LogError("ReceiveWebAction:" + json);
        Dictionary <string, System.Object> dic = JsonConvert.DeserializeObject <Dictionary <string, System.Object> >(json);
        string action = dic["Action"].ToString();

        switch (action)
        {
        case "UserLogin":
            string       callback;
            UserDBHelper userDBLogin = new UserDBHelper();
            try
            {
                User   user    = userDBLogin.getUser(dic["param1"].ToString(), dic["param2"].ToString(), dic["param3"].ToString());
                string userStr = JsonConvert.SerializeObject(user);
                if (userName == null)
                {
                    userName = user.Name;
                }
                if (user != null)
                {
                    callback       = "{\"Action\":\"LoginCallback\",\"param1\":\"success\",\"param2\":" + userStr + "}";
                    MySession.user = user;
                }
                else
                {
                    callback       = "{\"Action\":\"LoginCallback\",\"param1\":\"failed\",\"param2\":\"用户名密码错误!\"}";
                    MySession.user = null;
                }
            }
            catch (Exception)
            {
                callback = "{\"Action\":\"LoginCallback\",\"param1\":\"failed\",\"param2\":\"服务器配置错误!\"}";
            }
            UnityToWeb(callback);
            break;

        case "MusicOnOff":     //音乐开关
            if (dic["param1"].ToString() == "0")
            {
                AudioManager.getInstance().AudioPause(global::AudioManager.MusicNumType.groundMusic);
            }
            else
            {
                AudioManager.getInstance().AudioPlay(global::AudioManager.MusicNumType.groundMusic);
            }
            break;

        case "VoiceControl":     //音量控制
            AudioManager.getInstance().SetAudioVolume(global::AudioManager.MusicNumType.groundMusic, int.Parse(dic["param1"].ToString()) / 20.0f);
            break;

        case "GetExternalLinks":     //获取链接数据-知识界面
            string            callbackExternalLinks;
            InfoLinksDBHelper externalLinksDB  = new InfoLinksDBHelper();
            string            externalLinksStr = externalLinksDB.getGetLinks(dic["param1"].ToString(), int.Parse(dic["param2"].ToString()), int.Parse(dic["param3"].ToString()));
            int totalNum = externalLinksDB.getGetTotalLinksNum(dic["param1"].ToString());
            callbackExternalLinks = "{\"Action\":\"GetExternalLinksCallback\",\"param1\":" + externalLinksStr + ",\"param2\":\"" + totalNum + "\"}";
            Debug.LogError("callback:" + callbackExternalLinks);
            UnityToWeb(callbackExternalLinks);
            break;

        case "GetExternalLinksByPage":     //通过page获取链接数据 -知识界面
            string            callbackLinksByPage;
            InfoLinksDBHelper linkByPageDB  = new InfoLinksDBHelper();
            string            linkByPageStr = linkByPageDB.getGetLinks(dic["param1"].ToString(), int.Parse(dic["param2"].ToString()), int.Parse(dic["param3"].ToString()));
            callbackLinksByPage = "{\"Action\":\"GetExternalLinksByPageCallback\",\"param1\":\"" + linkByPageStr + "\"}";
            UnityToWeb(callbackLinksByPage);
            break;

        case "DeleteExternalLinks":     //通过page获取链接数据 -知识界面
            string            DeleteExternalLinksResult = "";
            InfoLinksDBHelper DeleteExternalLinksDB     = new InfoLinksDBHelper();
            bool DeleteExternalLinksisSuccessed         = DeleteExternalLinksDB.deleteLink(int.Parse(dic["param1"].ToString()));
            if (DeleteExternalLinksisSuccessed)
            {
                DeleteExternalLinksResult = "success";
            }
            else
            {
                DeleteExternalLinksResult = "faild";
            }
            string DeleteExternalLinksCallback = "{\"Action\":\"DeleteExternalLinksCallback\",\"param1\":\"" + DeleteExternalLinksResult + "\"}";
            UnityToWeb(DeleteExternalLinksCallback);
            break;

        case "AddExternalLinks":
            string            AddExternalLinksResult = "";
            InfoLinksDBHelper AddExternalLinksDB     = new InfoLinksDBHelper();
            LinkInfo          info = new LinkInfo();
            info.Type    = dic["param1"].ToString();
            info.Address = dic["param2"].ToString();
            bool AddExternalLinksisSuccessed = AddExternalLinksDB.addLink(info);
            if (AddExternalLinksisSuccessed)
            {
                AddExternalLinksResult = "success";
            }
            else
            {
                AddExternalLinksResult = "faild";
            }
            string AddExternalLinksCallback = "{\"Action\":\"AddExternalLinksCallback\",\"param1\":\"" + AddExternalLinksResult + "\",\"param2\":\"" + info.Type + "\"}";
            UnityToWeb(AddExternalLinksCallback);
            break;

        case "EditExternalLinks":
            Dictionary <string, string> EditExternalLinksdicTemp = JsonConvert.DeserializeObject <Dictionary <string, string> >(dic["param1"].ToString());
            string            EditExternalLinksResult            = "";
            InfoLinksDBHelper EditExternalLinksDB   = new InfoLinksDBHelper();
            LinkInfo          EditExternalLinksinfo = new LinkInfo();
            EditExternalLinksinfo.Id = int.Parse(EditExternalLinksdicTemp["Id"]);
            //EditExternalLinksinfo.Type = EditExternalLinksdicTemp["type"];
            EditExternalLinksinfo.Address = EditExternalLinksdicTemp["Address"];
            bool EditExternalLinksisSuccessed = EditExternalLinksDB.updateLink(EditExternalLinksinfo);
            if (EditExternalLinksisSuccessed)
            {
                EditExternalLinksResult = "success";
            }
            else
            {
                EditExternalLinksResult = "faild";
            }
            string EditExternalLinksCallback = "{\"Action\":\"AddExternalLinksCallback\",\"param1\":\"" + EditExternalLinksResult + "\"}";
            UnityToWeb(EditExternalLinksCallback);
            break;

        case "OpenExternalLinks":     //根据type,link打开外部链接
            OpenLink(dic["param1"].ToString(), dic["param2"].ToString());
            break;

        case "updateLinks":
            if ((dic["param1"].ToString()).Equals("ppt"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Ppt, updateLinks, dic["param2"].ToString());
            }
            else if ((dic["param1"].ToString()).Equals("word"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Word, updateLinks, dic["param2"].ToString());
            }
            else if ((dic["param1"].ToString()).Equals("excel"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Excel, updateLinks, dic["param2"].ToString());
            }
            else if ((dic["param1"].ToString()).Equals("video"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Vedio, updateLinks, dic["param2"].ToString());
            }
            break;

        case "UpExternalLinks":
            if ((dic["param1"].ToString()).Equals("ppt"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Ppt, UpLinks);
            }
            else if ((dic["param1"].ToString()).Equals("word"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Word, UpLinks);
            }
            else if ((dic["param1"].ToString()).Equals("excel"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Excel, UpLinks);
            }
            else if ((dic["param1"].ToString()).Equals("video"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Vedio, UpLinks);
            }
            else if ((dic["param1"].ToString()).Equals("all"))
            {
                UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.AllType, UpLinks);
            }
            break;

        case "EnterScene":     //根据进入培训场景
            switch (dic["param2"].ToString())
            {
            case "sbrz":
                UIManager.getInstance().enterEquipKnow("DeviceKnow1", (TrainUI.TrainMode) int.Parse(dic["param3"].ToString()));
                break;

            case "dlyl":
                UIManager.getInstance().enterTrain(dic["param1"].ToString(), "电路原理", (TrainUI.TrainMode) int.Parse(dic["param3"].ToString()));
                break;

            case "sbcj":
                UIManager.getInstance().enterTrain(dic["param1"].ToString(), "设备拆解", (TrainUI.TrainMode) int.Parse(dic["param3"].ToString()));
                break;

            case "sbzz":
                UIManager.getInstance().enterTrain(dic["param1"].ToString(), "设备组装", (TrainUI.TrainMode) int.Parse(dic["param3"].ToString()));
                break;

            case "sbxs":
                UIManager.getInstance().enterTrain(dic["param1"].ToString(), "设备巡视", (TrainUI.TrainMode) int.Parse(dic["param3"].ToString()));
                break;

            case "sbjx":
                UIManager.getInstance().enterTrain(dic["param1"].ToString(), "设备检修", (TrainUI.TrainMode) int.Parse(dic["param3"].ToString()));
                break;

            case "DBQgz":
                UIManager.getInstance().enterTrain(dic["param1"].ToString(), "设备故障", (TrainUI.TrainMode) int.Parse(dic["param3"].ToString()));
                break;
            }
            break;

        case "StudentRegister":
            Dictionary <string, string> dicTemp = JsonConvert.DeserializeObject <Dictionary <string, string> >(dic["param1"].ToString());
            UserDBHelper userDBStu = new UserDBHelper();
            User         userStu   = new User();
            userStu.Name      = dicTemp["name"];
            userStu.Sex       = dicTemp["sex"];
            userStu.Phone     = dicTemp["phone"];
            userStu.IdCard    = dicTemp["ide"];
            userStu.Term      = dicTemp["term"];
            userStu.Workshop  = dicTemp["workshop"];
            userStu.Group     = dicTemp["team"];
            userStu.AccountID = dicTemp["id"];
            userStu.Pwd       = dicTemp["pwd"];
            bool isSuccessed = userDBStu.addUser(userStu);
            //“success”:成功 “faild”:失败
            string result = "";
            if (isSuccessed)
            {
                result = "success";
            }
            else
            {
                result = "faild";
            }
            string callBackStudentRegister = "{\"Action\":\"StudentRegisterCallback\",\"param1\":\"" + result + "\"}";
            UnityToWeb(callBackStudentRegister);
            break;

        case "StudentEdit":
            Dictionary <string, string> dicTempStuEdit = JsonConvert.DeserializeObject <Dictionary <string, string> >(dic["param1"].ToString());
            UserDBHelper userDBStuEdit = new UserDBHelper();
            User         userStuEdit   = new User();
            userStuEdit.Name      = dicTempStuEdit["name"];
            userStuEdit.Sex       = dicTempStuEdit["sex"];
            userStuEdit.Phone     = dicTempStuEdit["phone"];
            userStuEdit.IdCard    = dicTempStuEdit["ide"];
            userStuEdit.Term      = dicTempStuEdit["term"];
            userStuEdit.Workshop  = dicTempStuEdit["workshop"];
            userStuEdit.Group     = dicTempStuEdit["team"];
            userStuEdit.AccountID = dicTempStuEdit["id"];
            userStuEdit.Pwd       = dicTempStuEdit["pwd"];
            bool isSuccessedStuEdit = userDBStuEdit.updateUser(userStuEdit);

            //“success”:成功 “faild”:失败
            string resultStuEdit = "";
            if (isSuccessedStuEdit)
            {
                resultStuEdit = "success";
            }
            else
            {
                resultStuEdit = "faild";
            }
            string callBackStuEdit = "{\"Action\":\"StudentEditCallback\",\"param1\":\"" + resultStuEdit + "\"}";
            UnityToWeb(callBackStuEdit);
            break;

        case "StudentDelete":
            UserDBHelper userInfoDBStudentDelete        = new UserDBHelper();
            bool         isSuccessedStudentDelete       = userInfoDBStudentDelete.deleteUser(int.Parse(dic["param1"].ToString()));
            string       resultisSuccessedStudentDelete = "";
            if (isSuccessedStudentDelete)
            {
                resultisSuccessedStudentDelete = "success";
            }
            else
            {
                resultisSuccessedStudentDelete = "faild";
            }
            string callBackStudentDelete = "{\"Action\":\"StudentDeleteCallback\",\"param1\":\"" + resultisSuccessedStudentDelete + "\"}";
            UnityToWeb(callBackStudentDelete);
            break;

        case "GetStuInfo":
            UserDBHelper userInfoDB      = new UserDBHelper();
            int          userNum         = userInfoDB.getTotalXueyuanUserNum();
            List <User>  users           = userInfoDB.getXueyuanUserByPage(int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString()));
            string       callBackStuInfo = "{\"Action\":\"GetStuInfoCallback\",\"param1\":" + JsonConvert.SerializeObject(users) + ",\"param2\":\"" + userNum + "\"}";
            Debug.Log(callBackStuInfo);
            UnityToWeb(callBackStuInfo);
            break;

        case "GetStuScoreInfo":
            string stuScoreBackJson = gradeManager.gradeManager(dic["param1"].ToString(), int.Parse(dic["param2"].ToString()), int.Parse(dic["param3"].ToString()));
            UnityToWeb(stuScoreBackJson);
            break;

        case "TestBack":
            //当前成绩返回
            if (UIManager.getInstance().getCurrentUIType() == UIType.TrainUI)
            {
                UIManager.getInstance().trainUI.backMenu();
            }
            else if (UIManager.getInstance().getCurrentUIType() == UIType.CircuitUI)
            {
                UIManager.getInstance().circuitUI.backMenu();
            }
            break;

        case "TestAgin":
            //当前成绩页面再考一次
            if (UIManager.getInstance().getCurrentUIType() == UIType.TrainUI)
            {
                UIManager.getInstance().trainUI.afreshExam();
            }
            else if (UIManager.getInstance().getCurrentUIType() == UIType.CircuitUI)
            {
                UIManager.getInstance().circuitUI.afreshExam();
            }
            break;

        case "CheckCircuitErrorInfo":
            break;

        case "CheckErrorInfo":
            if (int.Parse(dic["param1"].ToString()) == 2)
            {
                UIManager.getInstance().circuitUI.cause(int.Parse(dic["param2"].ToString()));
            }
            else
            {
                UIManager.getInstance().trainUI.cause(int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString()));
            }
            break;

        case "getTwoQuestionTest":
            string topicsJson = JsonConvert.SerializeObject(gradeManager.getTopic2Ds(int.Parse(dic["param1"].ToString())));
            float  examTime   = gradeManager.getExamTimeById(int.Parse(dic["param1"].ToString()));
            UnityToWeb("getTwoQuestionTest", topicsJson, examTime.ToString());
            break;

        case "getTwoTestScore":
            string twoScore = gradeManager.examGrade2D(dic["param1"].ToString());
            UnityToWeb("getTwoTestScoreBack", twoScore);
            break;

        case "AddTwoQuestion":
            string twoQuestionBack = "";
            if (gradeManager.topic2DResolve(dic["param1"].ToString()))
            {
                twoQuestionBack = "success";
            }
            else
            {
                twoQuestionBack = "failed";
            }
            UnityToWeb("AddTwoQuestionCallback", twoQuestionBack);
            break;

        case "AddTwoQuestionImg":
            UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Image, uploadImg, dic["param1"].ToString());
            break;

        case "GetTwoQuestion":
            int            currentPage          = int.Parse(dic["param1"].ToString());
            int            pageNum              = int.Parse(dic["param2"].ToString());
            int            SubjectId            = int.Parse(dic["SubjectId"].ToString());
            List <Topic2D> topics               = gradeManager.getTopic2Ds(SubjectId, currentPage, pageNum);
            int            topicCount           = gradeManager.getTopic2DCount(SubjectId);
            float          scoreCount           = gradeManager.getTopic2DScoreCount(SubjectId);
            string         questionCallbackJson = "{\"Action\":\"GetTwoQuestionCallback\",\"param1\":" + JsonConvert.SerializeObject(topics) + ",\"param2\":\"" + topicCount.ToString() + "\",\"param3\":\"" + scoreCount.ToString() + "\"}";
            UnityToWeb(questionCallbackJson);
            break;

        case "DeleteTwoQuestion":
            if (gradeManager.deleteTopic2D(int.Parse(dic["param1"].ToString())))
            {
                UnityToWeb("DeleteTwoQuestionCallback", "success");
            }
            else
            {
                UnityToWeb("DeleteTwoQuestionCallback", "failed");
            }
            break;

        case "UpdateTwoQuestion":
            if (gradeManager.updateTopic2DResolve(dic["param1"].ToString()))
            {
                UnityToWeb("UpdateTwoQuestionCallback", "success");
            }
            else
            {
                UnityToWeb("UpdateTwoQuestionCallback", "failed");
            }
            break;

        case "getTestScorePage":
            string scorePageJson = gradeManager.getHistoryGrade(int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString()));
            UnityToWeb("getTestScoreBack", scorePageJson);
            break;

        case "getTestCharts":
            string chartsJson = gradeManager.getGradeCharts(int.Parse(dic["param1"].ToString()));
            UnityToWeb("getTestChartsBack", chartsJson);
            break;

        ///update score;
        case "updateTwoScore":
            UnityToWeb("updateTwoScoreCallback", gradeManager.updateTopic2DScore(int.Parse(dic["param1"].ToString()), float.Parse(dic["param2"].ToString()), int.Parse(dic["param3"].ToString())).ToString());
            break;

        case "updateThreeScore":
            UnityToWeb("updateThreeScoreCallback", gradeManager.updateTopic3DScore(int.Parse(dic["param1"].ToString()), float.Parse(dic["param2"].ToString()), int.Parse(dic["param3"].ToString())).ToString());
            break;

        case "updateFourScore":
            UnityToWeb("updateFourScoreCallback", gradeManager.updateTopic3DScore(int.Parse(dic["param1"].ToString()), float.Parse(dic["param2"].ToString()), int.Parse(dic["param3"].ToString())).ToString());
            break;

        ////param1 : score//15 5 2   14 1 2
        case "updateCircuitScore":
            //DataBackup();
            //UnityToWeb("updateCircuitScoreCallback", gradeManager.updateTopicCircuitScore(int.Parse(dic["param2"].ToString()), float.Parse(dic["param4"].ToString()), int.Parse(dic["param1"].ToString()), dic["param3"].ToString(), char.Parse(dic["param5"].ToString())).ToString());
            UnityToWeb("updateCircuitScoreCallback", gradeManager.updateTopicCircuitScore(int.Parse(dic["param2"].ToString()), float.Parse(dic["param1"].ToString()), int.Parse(dic["param3"].ToString())).ToString());
            break;

        case "getCircuits":
            UnityToWeb("getCircuitsCallback", JsonConvert.SerializeObject(gradeManager.getCircuitTopics()));
            break;

        case "updateIsExam":
            UnityToWeb("updateIsExamCallback", gradeManager.updateIsExam(int.Parse(dic["param1"].ToString()), char.Parse(dic["param2"].ToString())).ToString());
            break;

        case "GetThreeQuestion":
            List <Topic3D> topic3Ds     = gradeManager.getTopic3Ds(int.Parse(dic["param3"].ToString()), int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString()));
            int            topic3DCount = gradeManager.getTopic3DCount(int.Parse(dic["param3"].ToString()));
            float          topic3DScore = gradeManager.getTopic3DScoreCount(int.Parse(dic["param3"].ToString()));
            string         ThreeQuestionCallbackJson = "{\"Action\":\"GetThreeQuestionCallback\",\"param1\":" + JsonConvert.SerializeObject(topic3Ds) + ",\"param2\":\"" + topic3DCount.ToString() + "\",\"param3\":\"" + topic3DScore.ToString() + "\",\"param4\":\"" + dic["param3"].ToString() + "\",\"param5\":\"" + (gradeManager.getExamSubject(int.Parse(dic["param3"].ToString())).IsExam ? "1" : "0") + "\"}";
            UnityToWeb(ThreeQuestionCallbackJson);
            break;

        ////four
        case "GetFourQuestion":
            List <CircuitTopicNew> topic4Ds = gradeManager.getTopicCircuitTopicNew(int.Parse(dic["param3"].ToString()));
            int    topic4DCount             = gradeManager.getTopicCircuitCount(int.Parse(dic["param3"].ToString()));
            float  topic4DScore             = gradeManager.getTopicCircuitScoreCount(int.Parse(dic["param3"].ToString()));
            string FourQuestionCallbackJson = "{\"Action\":\"GetFourQuestionCallback\",\"param1\":" + JsonConvert.SerializeObject(topic4Ds) + ",\"param2\":\"" + topic4DCount.ToString() + "\",\"param3\":\"" + topic4DScore.ToString() + "\",\"param4\":\"" + dic["param3"].ToString() + "\",\"param5\":\"" + (gradeManager.getExamSubject(int.Parse(dic["param3"].ToString())).IsExam ? "1" : "0") + "\"}";
            UnityToWeb(FourQuestionCallbackJson);
            break;
        //new four
        ////


        case "updateSubjectExam":
            if (gradeManager.updateSubjectExam(int.Parse(dic["param1"].ToString()), dic["param2"].ToString()))
            {
                UnityToWeb("updateSubjectExamCallback", "success");
            }
            else
            {
                UnityToWeb("updateSubjectExamCallback", "faild");
            }
            break;

        case "BackToSbrzStudy":
            UIManager.getInstance().equipKnowUI.changeMode(TrainUI.TrainMode.Study);
            break;

        case "BackToMenu":
            UIManager.getInstance().equipKnowUI.backMenu();
            break;

        case "ImportStuInfo":
            UIManager.getInstance().GetComponent <OpenFile>().OpenFileByType(OpenFile.FileType.Excel, InputData);
            break;

        case "PlayMusicByID":
            PlayMusicByID(int.Parse(dic["param1"].ToString()));
            break;

        case "updateAllTopic3DScore":
            gradeManager.updateAllTopic3DScore(int.Parse(dic["param3"].ToString()));
            List <Topic3D> topic3ds     = gradeManager.getTopic3Ds(int.Parse(dic["param3"].ToString()), int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString()));
            int            topic3dCount = gradeManager.getTopic3DCount(int.Parse(dic["param3"].ToString()));
            float          topic3dScore = gradeManager.getTopic3DScoreCount(int.Parse(dic["param3"].ToString()));
            string         updateAllTopic3DScoreJson = "{\"Action\":\"updateAllTopic3DScoreCallBack\",\"param1\":" + JsonConvert.SerializeObject(topic3ds) + ",\"param2\":\"" + topic3dCount.ToString() + "\",\"param3\":\"" + topic3dScore.ToString() + "\",\"param4\":\"" + dic["param3"].ToString() + "\",\"param5\":\"" + (gradeManager.getExamSubject(int.Parse(dic["param3"].ToString())).IsExam ? "1" : "0") + "\"}";
            UnityToWeb(updateAllTopic3DScoreJson);
            break;

        case "updateAllTopic2DScore":
            gradeManager.updateAllTopic2DScore(int.Parse(dic["param3"].ToString()));
            List <Topic2D> topic2ds     = gradeManager.getTopic2Ds(int.Parse(dic["param3"].ToString()), int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString()));
            int            topic2dCount = gradeManager.getTopic2DCount(int.Parse(dic["param3"].ToString()));
            float          topic2dScore = gradeManager.getTopic2DScoreCount(int.Parse(dic["param3"].ToString()));
            string         updateAllTopic2DScoreJson = "{\"Action\":\"updateAllTopic2DScoreCallBack\",\"param1\":" + JsonConvert.SerializeObject(topic2ds) + ",\"param2\":\"" + topic2dCount.ToString() + "\",\"param3\":\"" + topic2dScore.ToString() + "\",\"param4\":\"" + dic["param3"].ToString() + "\",\"param5\":\"" + (gradeManager.getExamSubject(int.Parse(dic["param3"].ToString())).IsExam ? "1" : "0") + "\"}";
            UnityToWeb(updateAllTopic2DScoreJson);
            break;

        case "closeSystem":
            UIManager.getInstance().exitSystem();
            break;

        case "StopMusicByID":
            AudioManager.getInstance().AudioStop(AudioManager.MusicNumType.realtimeMusic);
            break;

        case "GetDurationCharts":
            Dictionary <string, int> grades = gradeManager.GetDurationCharts(int.Parse(dic["param1"].ToString()));
            string[] ExamTime = new string[grades.Count];
            float[]  Grade    = new float[grades.Count];
            int      count    = 0;
            foreach (KeyValuePair <string, int> kvp in grades)
            {
                ExamTime[count] = kvp.Key;
                Grade[count]    = kvp.Value;
                count++;
            }
            string GetDurationChartsJson = "{\"Action\":\"GetDurationChartsCallback\",\"param1\":" + JsonConvert.SerializeObject(ExamTime) + ",\"param2\":" + JsonConvert.SerializeObject(Grade) + "}";
            Debug.Log(GetDurationChartsJson);
            UnityToWeb(GetDurationChartsJson);
            break;

        case "GetScoreCharts":
            Dictionary <string, float> gradeScore = gradeManager.GetScoreCharts(int.Parse(dic["param1"].ToString()));
            string[] ExamTimeScore = new string[gradeScore.Count];
            float[]  GradeScore    = new float[gradeScore.Count];
            int      countScore    = 0;
            foreach (KeyValuePair <string, float> kvp in gradeScore)
            {
                ExamTimeScore[countScore] = kvp.Key;
                GradeScore[countScore]    = kvp.Value;
                countScore++;
            }
            string GetScoreChartsJson = "{\"Action\":\"GetScoreChartsCallback\",\"param1\":" + JsonConvert.SerializeObject(ExamTimeScore) + ",\"param2\":" + JsonConvert.SerializeObject(GradeScore) + "}";
            Debug.Log(GetScoreChartsJson);
            UnityToWeb(GetScoreChartsJson);
            break;

        case "getSumStuDate":
            string getSumStuCallbackJson = "{\"Action\":\"getSumStuCallback\",\"param1\":" + JsonConvert.SerializeObject(gradeManager.getSumStuDate(dic["param1"].ToString())) + "}";
            UnityToWeb(getSumStuCallbackJson);
            break;

        case "getSumCurveDate":
            string getSumCurveCallbackJson = "{\"Action\":\"getSumCurveCallback\",\"param1\":" + JsonConvert.SerializeObject(gradeManager.getSumCurveDate()) + "}";
            UnityToWeb(getSumCurveCallbackJson);
            break;

        case "SubmitReportDate":
            string wordPath = createWord(dic["param1"].ToString());
            string submitBack;
            string SubmitReportDateCallbackJson;
            if (wordPath == null || wordPath == "")
            {
                submitBack = "failed";
            }
            else
            {
                submitBack = "success";
            }
            SubmitReportDateCallbackJson = "{\"Action\":\"SubmitReportDateCallback\",\"param1\":\"" + submitBack + "\",\"param2\":\"" + wordPath + "\"}";
            UnityToWeb(SubmitReportDateCallbackJson);
            break;

        case "SystemBackup":
            DoBackup();
            string BackupJson = "{\"Action\":\"SystemBackupCallback\",\"param1\":\"1\"}";
            UnityToWeb(BackupJson);
            break;

        case "RestoreBackup":
            restore(int.Parse(dic["param1"].ToString()));
            string RestoreJson = "{\"Action\":\"RestoreBackupCallback\",\"param1\":\"1\"}";
            UnityToWeb(RestoreJson);
            break;

        case "GetSystemBackup":
            //string GetSystemBackupJson = "{\"Action\":\"GetSystemBackupCallback\",\"param1\":" + JsonConvert.SerializeObject(GetSystemBackup(int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString()))) + "}";
            UnityToWeb(GetSystemBackup(int.Parse(dic["param1"].ToString()), int.Parse(dic["param2"].ToString())));
            break;

        case "DeleteBackup":
            string back = "";
            if (DeleteBackup(int.Parse(dic["param1"].ToString())))
            {
                back = "success";
            }
            else
            {
                back = "failed";
            }
            string deleteBackupJson = "{\"Action\":\"DeleteBackupCallback\",\"param1\":\"" + back + "\"}";
            UnityToWeb(deleteBackupJson);
            break;
        }
    }
Ejemplo n.º 34
0
        public static LinkInfo TryParseOpenGraphMeta(this LinkInfo result, HtmlDocument document, bool includeDescription)
        {
            var metaTags = document.DocumentNode.SelectNodes("//meta");

            if (metaTags != null)
            {
                foreach (var tag in metaTags)
                {
                    var tagName     = tag.Attributes["name"];
                    var tagContent  = tag.Attributes["content"];
                    var tagProperty = tag.Attributes["property"];

                    if (tagName != null && tagContent != null)
                    {
                        switch (tagName.Value.ToLower())
                        {
                        case "title":
                            result.Title = tagContent.Value;
                            break;

                        case "description":
                            if (includeDescription)
                            {
                                result.Description = tagContent.Value;
                            }
                            break;

                        case "twitter:title":
                            result.Title = string.IsNullOrWhiteSpace(result.Title) ? tagContent.Value : result.Title;
                            break;

                        case "twitter:description":
                            if (includeDescription)
                            {
                                result.Description = string.IsNullOrWhiteSpace(result.Description) ? tagContent.Value : result.Description;
                            }
                            break;

                        case "twitter:image":
                            result.ImageUrl = result.ImageUrl ?? (!string.IsNullOrWhiteSpace(tagContent.Value) ? new Uri(tagContent.Value): null);
                            break;
                        }
                    }
                    else if (tagProperty != null && tagContent != null)
                    {
                        switch (tagProperty.Value.ToLower())
                        {
                        case "og:title":
                            result.Title = string.IsNullOrWhiteSpace(result.Title) ? tagContent.Value : result.Title;
                            break;

                        case "og:description":
                            if (includeDescription)
                            {
                                result.Description = string.IsNullOrWhiteSpace(result.Description) ? tagContent.Value : result.Description;
                            }
                            break;

                        case "og:image":
                            result.ImageUrl = result.ImageUrl == null ? new Uri(tagContent.Value.EnforceHttps()) : new Uri(result.ImageUrl.ToString().EnforceHttps());
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 35
0
    // создаёт экземпляр PartInfo с настройками по-умолчанию.
    // toEnd - добавляем в конец цепи или в начало
    LinkInfo createBasicPart(int prefabId, bool toEnd = true)
    {
        LinkInfo p = new LinkInfo();

        p.obj      = Instantiate <GameObject>(prefabsList[prefabId]);
        p.prefabId = prefabId;

        if (chainMode == ChainMode.None)
        {
            p.prefabIdNext = p.prefabIdPrev = p.prefabId;
        }
        else if (chainMode == ChainMode.Queue)
        {
            p.prefabIdNext = p.prefabId + 1 == prefabsList.Count ? 0 : p.prefabId + 1;
            p.prefabIdPrev = p.prefabId - 1 < 0 ? prefabsList.Count - 1 : p.prefabId - 1;
        }
        else if (chainMode == ChainMode.Random)
        {
            if (toEnd)
            {
                // если звено первое, то в prefabIdPrev записываем случайно число, иначе id предыдущего звена (последнего в цепи)
                if (links.Count == 0)
                {
                    p.prefabIdPrev = UnityEngine.Random.Range(0, prefabsList.Count);
                }
                else
                {
                    p.prefabIdPrev = links[linksCount - 1].prefabId;
                }

                p.prefabIdNext = UnityEngine.Random.Range(0, prefabsList.Count);
            }
            else
            {
                p.prefabIdPrev = UnityEngine.Random.Range(0, prefabsList.Count);
                if (links.Count == 0)
                {
                    p.prefabIdNext = UnityEngine.Random.Range(0, prefabsList.Count);
                }
                else
                {
                    p.prefabIdNext = links[0].prefabId;
                }
            }
        }

        p.width           = _prefabsListWidths[prefabId];
        p.widthHalf       = p.width / 2;
        p.widthScaled     = p.width * scaleFactorX;
        p.widthScaledHalf = p.widthScaled / 2;

        p.obj.transform.localScale = new Vector3(scaleFactorX, scaleFactorY, 1);

        p.rb2D = p.obj.GetComponent <Rigidbody2D>() == null?p.obj.AddComponent <Rigidbody2D>() : p.obj.GetComponent <Rigidbody2D>();

        p.hingleJoint_1 = p.obj.AddComponent <HingeJoint2D>();
        p.obj.AddComponent <Link>().removeMeFromList += removeLinkHandler;   //подписка на удаление, но если это звено было создано в эдиторе,

        p.obj.transform.SetParent(this.transform);

        return(p);
    }
Ejemplo n.º 36
0
 public static GraphModel ParseGraphJson(string json, string root)
 {
     ZLog.Log("ParseGraphJson..." + json.Length);
     if (string.IsNullOrEmpty(json))
     {
         return(null);
     }
     try
     {
         var        obj   = JsonMapper.ToObject(json);
         GraphModel model = new GraphModel(root)
         {
             name = (string)obj["name"],
         };
         if (((IDictionary)obj).Contains("parent"))
         {
             model.Parent = (string)obj["parent"];
         }
         var center = (string)obj["center"];
         model.SetCenter(center);
         var nodes = obj["nodes"];
         if (nodes != null && nodes.IsArray)
         {
             foreach (JsonData item in nodes)
             {
                 NodeInfo node = new NodeInfo
                 {
                     UID    = (string)item["uid"],
                     name   = (string)item["name"],
                     avatar = (string)item["avatar"],
                     type   = (string)item["type"],
                     parent = center
                 };
                 if (string.IsNullOrEmpty(node.avatar))
                 {
                     node.avatar = Path.Combine(root, "cover/" + node.name + ".png");
                 }
                 node.fullPath = Path.Combine(root, "entity/entity_" + node.UID + ".json");
                 model.AddNode(node, null);
             }
         }
         var edges = obj["edges"];
         if (edges != null && edges.IsArray)
         {
             foreach (JsonData item in edges)
             {
                 LinkInfo edge = new LinkInfo
                 {
                     UID       = (string)item["uid"],
                     name      = (string)item["name"],
                     direction = (DirectionType)(int)item["direction"]
                 };
                 var from = (string)item["from"];
                 edge.from = model.GetNode(from);
                 var to = (string)item["to"];
                 edge.to = model.GetNode(to);
                 if (((IDictionary)item).Contains("type"))
                 {
                     edge.type = (string)item["type"];
                 }
                 model.AddEdge(edge);
             }
             model.CheckVirtualNodes();
         }
         return(model);
     }
     catch (Exception e)
     {
         ZLog.Warning(json);
         ZLog.Warning(e.Message);
         return(null);
     }
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Create a ShellLing from a given byte array
        /// </summary>
        /// <param name="ba">The byte array</param>
        /// <returns>A Shortcut object</returns>
        public static new Shortcut FromByteArray(byte[] ba)
        {
            Shortcut lnk = new Shortcut();

            #region SHELL_LINK_HEADER
            ShellLinkHeader Header     = ShellLinkHeader.FromByteArray(ba);
            UInt32          HeaderSize = BitConverter.ToUInt32(ba, 0);
            Boolean         IsUnicode  = (Header.LinkFlags & LinkFlags.IsUnicode) != 0;
            lnk.LinkFlags      = Header.LinkFlags;
            lnk.FileAttributes = Header.FileAttributes;
            lnk.CreationTime   = Header.CreationTime;
            lnk.AccessTime     = Header.AccessTime;
            lnk.WriteTime      = Header.WriteTime;
            lnk.FileSize       = Header.FileSize;
            lnk.IconIndex      = Header.IconIndex;
            lnk.ShowCommand    = Header.ShowCommand;
            lnk.HotKey         = Header.HotKey;
            ba = ba.Skip((int)HeaderSize).ToArray();
            #endregion // SHELL_LINK_HEADER

            #region LINKTARGET_IDLIST
            if ((Header.LinkFlags & LinkFlags.HasLinkTargetIDList) != 0)
            {
                lnk.LinkTargetIDList = LinkTargetIDList.FromByteArray(ba);
                UInt16 IDListSize = BitConverter.ToUInt16(ba, 0);
                ba = ba.Skip(IDListSize + 2).ToArray();
            }
            #endregion // LINKTARGET_IDLIST

            #region LINKINFO
            if ((Header.LinkFlags & LinkFlags.HasLinkInfo) != 0)
            {
                lnk.LinkInfo = LinkInfo.FromByteArray(ba);
                UInt32 LinkInfoSize = BitConverter.ToUInt32(ba, 0);
                ba = ba.Skip((int)LinkInfoSize).ToArray();
            }
            #endregion // LINKINFO

            #region STRING_DATA
            if ((Header.LinkFlags & LinkFlags.HasName) != 0)
            {
                if (lnk.StringData == null)
                {
                    lnk.StringData = new StringData(IsUnicode);
                }

                UInt16 CountCharacters = BitConverter.ToUInt16(ba, 0);
                if (IsUnicode)
                {
                    lnk.StringData.NameString = Encoding.Unicode.GetString(ba.Skip(2).Take(CountCharacters * 2).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters * 2 + 2).ToArray();
                }
                else
                {
                    lnk.StringData.NameString = Encoding.Default.GetString(ba.Skip(2).Take(CountCharacters).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters + 2).ToArray();
                }
            }

            if ((Header.LinkFlags & LinkFlags.HasRelativePath) != 0)
            {
                if (lnk.StringData == null)
                {
                    lnk.StringData = new StringData(IsUnicode);
                }

                UInt16 CountCharacters = BitConverter.ToUInt16(ba, 0);
                if (IsUnicode)
                {
                    lnk.StringData.RelativePath = Encoding.Unicode.GetString(ba.Skip(2).Take(CountCharacters * 2).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters * 2 + 2).ToArray();
                }
                else
                {
                    lnk.StringData.RelativePath = Encoding.Default.GetString(ba.Skip(2).Take(CountCharacters).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters + 2).ToArray();
                }
            }

            if ((Header.LinkFlags & LinkFlags.HasWorkingDir) != 0)
            {
                if (lnk.StringData == null)
                {
                    lnk.StringData = new StringData(IsUnicode);
                }

                UInt16 CountCharacters = BitConverter.ToUInt16(ba, 0);
                if (IsUnicode)
                {
                    lnk.StringData.WorkingDir = Encoding.Unicode.GetString(ba.Skip(2).Take(CountCharacters * 2).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters * 2 + 2).ToArray();
                }
                else
                {
                    lnk.StringData.WorkingDir = Encoding.Default.GetString(ba.Skip(2).Take(CountCharacters).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters + 2).ToArray();
                }
            }

            if ((Header.LinkFlags & LinkFlags.HasArguments) != 0)
            {
                if (lnk.StringData == null)
                {
                    lnk.StringData = new StringData(IsUnicode);
                }

                UInt16 CountCharacters = BitConverter.ToUInt16(ba, 0);
                if (IsUnicode)
                {
                    lnk.StringData.CommandLineArguments = Encoding.Unicode.GetString(ba.Skip(2).Take(CountCharacters * 2).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters * 2 + 2).ToArray();
                }
                else
                {
                    lnk.StringData.CommandLineArguments = Encoding.Default.GetString(ba.Skip(2).Take(CountCharacters).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters + 2).ToArray();
                }
            }

            if ((Header.LinkFlags & LinkFlags.HasIconLocation) != 0)
            {
                if (lnk.StringData == null)
                {
                    lnk.StringData = new StringData(IsUnicode);
                }

                UInt16 CountCharacters = BitConverter.ToUInt16(ba, 0);
                if (IsUnicode)
                {
                    lnk.StringData.IconLocation = Encoding.Unicode.GetString(ba.Skip(2).Take(CountCharacters * 2).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters * 2 + 2).ToArray();
                }
                else
                {
                    lnk.StringData.IconLocation = Encoding.Default.GetString(ba.Skip(2).Take(CountCharacters).ToArray()).TrimEnd(new char[] { (char)0 });
                    ba = ba.Skip(CountCharacters + 2).ToArray();
                }
            }
            #endregion // STRING_DATA

            #region EXTRA_DATA
            if (ba.Length >= 4)
            {
                lnk.ExtraData = ExtraData.FromByteArray(ba);
            }
            #endregion // EXTRA_DATA

            return(lnk);
        }
Ejemplo n.º 38
0
        public ActionResult RsvpLinkSg(string id, string message, bool?confirm, FormCollection formCollection, bool regrets = false)
        {
            var li = new LinkInfo(rsvplinkSTR, landingSTR, id, false);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                var meetingid  = li.a[0].ToInt();
                var emailid    = li.a[2].ToInt();
                var smallgroup = li.a[3];
                if (meetingid == 0 && li.a[0].EndsWith(".next"))
                {
                    var orgid    = li.a[0].Split('.')[0].ToInt();
                    var nextmeet = (from mm in CurrentDatabase.Meetings
                                    where mm.OrganizationId == orgid
                                    where mm.MeetingDate > DateTime.Now
                                    orderby mm.MeetingDate
                                    select mm).FirstOrDefault();
                    if (nextmeet == null)
                    {
                        return(Message("no meeting"));
                    }

                    meetingid = nextmeet.MeetingId;
                }
                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let meeting = CurrentDatabase.Meetings.SingleOrDefault(mm => mm.MeetingId == meetingid)
                                       let org = meeting.Organization
                                                 select new { p = pp, org, meeting }).Single();

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                {
                    throw new Exception("sorry, registration has been closed");
                }

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                {
                    throw new Exception("rsvp is no longer available");
                }

                if (q.org.Limit <= q.meeting.Attends.Count(aa => aa.Commitment == 1))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                var omb = OrganizationMember.Load(CurrentDatabase, li.pid.Value, q.meeting.OrganizationId) ??
                          OrganizationMember.InsertOrgMembers(CurrentDatabase,
                                                              q.meeting.OrganizationId, li.pid.Value, MemberTypeCode.Member, DateTime.Now, null, false);
                if (smallgroup.HasValue())
                {
                    omb.AddToGroup(CurrentDatabase, smallgroup);
                }

                li.ot.Used = true;
                CurrentDatabase.SubmitChanges();
                Attend.MarkRegistered(CurrentDatabase, li.pid.Value, meetingid, regrets ? AttendCommitmentCode.Regrets : AttendCommitmentCode.Attending);
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}: {regrets}", q.org.OrganizationId, li.pid);
                var setting = CurrentDatabase.CreateRegistrationSettings(q.meeting.OrganizationId);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg     = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(CurrentDatabase, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", q.meeting.MeetingDate.ToString2("f"));
                    var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);

                    CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                          q.org.OrganizationName,
                                          $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{q.meeting.MeetingDate.ToString2("f")}");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}Error: {regrets}", peopleid: li.pid);
                return(Message(ex.Message));
            }
            return(Message(message));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        PageTitle.TitleText = GetString("newsletter_issue_subscribersclicks.title");
        linkId = QueryHelper.GetInteger("linkid", 0);
        if (linkId == 0)
        {
            RequestHelper.EndResponse();
        }

        LinkInfo link = LinkInfoProvider.GetLinkInfo(linkId);

        EditedObject = link;

        IssueInfo issue = IssueInfoProvider.GetIssueInfo(link.LinkIssueID);

        EditedObject = issue;

        // Prevent accessing issues from sites other than current site
        if (issue.IssueSiteID != SiteContext.CurrentSiteID)
        {
            RedirectToResourceNotAvailableOnSite("Issue with ID " + link.LinkIssueID);
        }

        var listingWhereCondition = new WhereCondition().WhereEquals("ClickedLinkNewsletterLinkID", linkId);

        // Link's issue is the main A/B test issue
        if (issue.IssueIsABTest && !issue.IssueIsVariant)
        {
            // Get A/B test and its winner issue ID
            ABTestInfo test = ABTestInfoProvider.GetABTestInfoForIssue(issue.IssueID);
            if (test != null)
            {
                // Get ID of the same link from winner issue
                var winnerLink = LinkInfoProvider.GetLinks()
                                 .WhereEquals("LinkIssueID", test.TestWinnerIssueID)
                                 .WhereEquals("LinkTarget", link.LinkTarget)
                                 .WhereEquals("LinkDescription", link.LinkDescription)
                                 .TopN(1)
                                 .Column("LinkID")
                                 .FirstOrDefault();

                if (winnerLink != null)
                {
                    if (winnerLink.LinkID > 0)
                    {
                        // Add link ID of winner issue link
                        listingWhereCondition.Or(new WhereCondition().WhereEquals("ClickedLinkNewsletterLinkID", winnerLink.LinkID));
                    }
                }
            }
        }

        UniGrid.Pager.DefaultPageSize = PAGESIZE;
        UniGrid.Pager.ShowPageSize    = false;
        UniGrid.FilterLimit           = 1;
        fltOpenedBy.EmailColumn       = "ClickedLinkEmail";

        // Get click count by email
        UniGrid.DataSource = ClickedLinkInfoProvider.GetClickedLinks()
                             .Columns(
            new QueryColumn("ClickedLinkEmail"),
            new AggregatedColumn(AggregationType.Count, null).As("ClickCount")
            )
                             .GroupBy("ClickedLinkEmail")
                             .Where(listingWhereCondition)
                             .And()
                             .Where(fltOpenedBy.WhereCondition)
                             .OrderByDescending("ClickCount")
                             .Result;
    }
Ejemplo n.º 40
0
        // ReSharper disable once FunctionComplexityOverflow
        public ActionResult RegisterLink(string id, bool?showfamily, string source)
        {
            var li = new LinkInfo(registerlinkSTR, landingSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                if (!li.oid.HasValue)
                {
                    throw new Exception("missing orgid");
                }

                var linktype = li.a.Length > 3 ? li.a[3].Split(':') : "".Split(':');
                int?gsid     = null;
                if (linktype[0].Equal("supportlink"))
                {
                    gsid = linktype.Length > 1 ? linktype[1].ToInt() : 0;
                }

                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == li.oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == li.oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();
                }

                if (q.org == null)
                {
                    throw new Exception("org missing, bad link");
                }

                if (q.om == null && !gsid.HasValue && q.org.Limit <= q.org.RegLimitCount(CurrentDatabase))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                if (q.om == null && (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive))
                {
                    throw new Exception("sorry, registration has been closed");
                }

                DbUtil.LogActivity($"{registerlinkSTR}{landingSTR}", li.oid, li.pid);

                var url = string.IsNullOrWhiteSpace(source)
                    ? $"/OnlineReg/{li.oid}?registertag={id}"
                    : $"/OnlineReg/{li.oid}?registertag={id}&source={source}";
                if (gsid.HasValue)
                {
                    url += "&gsid=" + gsid;
                }

                if (showfamily == true)
                {
                    url += "&showfamily=true";
                }

                if (linktype[0].Equal("supportlink") && q.org.TripFundingPagesEnable && q.org.TripFundingPagesPublic)
                {
                    url = $"/OnlineReg/{li.oid}/Giving/?gsid={gsid}";
                }

                return(Redirect(url));
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{registerlinkSTR}{landingSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }
        }
Ejemplo n.º 41
0
        private S3Link(S3ClientCache clientCache, LinkInfo linker)
        {
            if (linker == null) throw new ArgumentNullException("linker");
            if (clientCache == null) throw new ArgumentNullException("clientCache");

            this.s3ClientCache = clientCache;
            this.linker = linker;
        }
Ejemplo n.º 42
0
        public ActionResult SendLink(string id, FormCollection formCollection)
        {
            var li = new LinkInfo(sendlinkSTR, landingSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                if (!li.oid.HasValue)
                {
                    throw new Exception("missing orgid");
                }

                var queueid  = li.a[2].ToInt();
                var linktype = li.a[3]; // for supportlink, this will also have the goerid
                var q        = (from pp in CurrentDatabase.People
                                where pp.PeopleId == li.pid
                                let org = CurrentDatabase.LoadOrganizationById(li.oid)
                                          select new { p = pp, org }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.LoadOrganizationById(oid)
                                   select new { p = pp, org }).Single();
                }

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                {
                    throw new Exception("sorry, registration has been closed");
                }

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                {
                    throw new Exception("sorry, registration is no longer available");
                }

                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}", li.oid, li.pid);

                var    expires = DateTime.Now.AddMinutes(CurrentDatabase.Setting("SendlinkExpireMinutes", "30").ToInt());
                string action  = (linktype.Contains("supportlink") ? "support" : "register for");
                string minutes = CurrentDatabase.Setting("SendLinkExpireMinutes", "30");
                var    c       = DbUtil.Content("SendLinkMessage");
                if (c == null)
                {
                    c = new Content
                    {
                        Name  = "SendLinkMessage",
                        Title = "Your Link for {org}",
                        Body  = @"
<p>Here is your temporary <a href='{url}'>LINK</a> to {action} {org}.</p>

<p>This link will expire at {time} ({minutes} minutes).
You may request another link by clicking the link in the original email you received.</p>

<p>Note: If you did not request this link, please ignore this email,
or contact the church if you need help.</p>
"
                    };
                    CurrentDatabase.Contents.InsertOnSubmit(c);
                    CurrentDatabase.SubmitChanges();
                }
                var url = EmailReplacements.RegisterLinkUrl(CurrentDatabase,
                                                            li.oid.Value, li.pid.Value, queueid, linktype, expires);
                var subject = c.Title.Replace("{org}", q.org.OrganizationName);
                var msg     = c.Body.Replace("{org}", q.org.OrganizationName)
                              .Replace("{time}", expires.ToString("f"))
                              .Replace("{url}", url)
                              .Replace("{action}", action)
                              .Replace("{minutes}", minutes)
                              .Replace("%7Burl%7D", url);

                var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);
                CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation

                return(Message($"Thank you, {q.p.PreferredName}, we just sent an email to {Util.ObscureEmail(q.p.EmailAddress)} with your link..."));
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }
        }
Ejemplo n.º 43
0
 public static void Unlink(LinkInfo info)
 {
     Links.Remove(info);
 }
Ejemplo n.º 44
0
        public ActionResult VoteLinkSg(string id, string message, bool?confirm, FormCollection formCollection)
        {
            var li = new LinkInfo(votelinkSTR, confirmSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                var smallgroup = li.a[4];

                if (!li.oid.HasValue)
                {
                    throw new Exception("orgid missing");
                }

                if (!li.pid.HasValue)
                {
                    throw new Exception("peopleid missing");
                }

                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == li.oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == li.oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();
                }

                if (q.org == null)
                {
                    throw new Exception("org missing, bad link");
                }
                if ((q.org.RegistrationTypeId ?? RegistrationTypeCode.None) == RegistrationTypeCode.None)
                {
                    throw new Exception("votelink is no longer active");
                }

                if (q.om == null && q.org.Limit <= q.org.RegLimitCount(CurrentDatabase))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                if (q.om == null &&
                    (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive))
                {
                    throw new Exception("sorry, registration has been closed");
                }

                var setting = CurrentDatabase.CreateRegistrationSettings(li.oid.Value);
                if (IsSmallGroupFilled(setting, li.oid.Value, smallgroup))
                {
                    throw new Exception("sorry, maximum limit has been reached for " + smallgroup);
                }

                var omb = OrganizationMember.Load(CurrentDatabase, li.pid.Value, li.oid.Value) ??
                          OrganizationMember.InsertOrgMembers(CurrentDatabase,
                                                              li.oid.Value, li.pid.Value, MemberTypeCode.Member, Util.Now, null, false);

                if (q.org.AddToSmallGroupScript.HasValue())
                {
                    var script = CurrentDatabase.Content(q.org.AddToSmallGroupScript);
                    if (script != null && script.Body.HasValue())
                    {
                        try
                        {
                            var pe = new PythonModel(Util.Host, "RegisterEvent", script.Body);
                            pe.instance.AddToSmallGroup(smallgroup, omb);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                omb.AddToGroup(CurrentDatabase, smallgroup);
                li.ot.Used = true;
                CurrentDatabase.SubmitChanges();

                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}: {smallgroup}", li.oid, li.pid);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg     = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(CurrentDatabase, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", smallgroup);
                    var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);

                    try
                    {
                        CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    }
                    catch (Exception ex)
                    {
                        CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                              q.org.OrganizationName,
                                              "There was a problem sending confirmation from org: " + ex.Message);
                    }
                    CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                          q.org.OrganizationName,
                                          $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{smallgroup}<br>(from votelink)");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }

            return(Message(message));
        }
Ejemplo n.º 45
0
 /// <summary>
 /// 修改
 /// </summary>
 /// <param name="link"></param>
 /// <returns></returns>
 public int UpdateLink(LinkInfo link)
 {
     return  _linkRepository.Update(link);
 }
Ejemplo n.º 46
0
        /// <summary>
        /// 转换实体
        /// </summary>
        /// <param name="read">OleDbDataReader</param>
        /// <returns>LinkInfo</returns>
        private static List<LinkInfo> DataReaderToList(OleDbDataReader read)
        {
            List<LinkInfo> list = new List<LinkInfo>();
            while (read.Read())
            {
                LinkInfo link = new LinkInfo();
                link.LinkId = Convert.ToInt32(read["Linkid"]);
                link.Type = Convert.ToInt32(read["Type"]);
                link.Name = Convert.ToString(read["Name"]);
                link.Href = Convert.ToString(read["Href"]);
                if (read["Position"] != DBNull.Value)
                {
                    link.Position = Convert.ToInt32(read["Position"]);
                }

                link.Target = Convert.ToString(read["Target"]);
                link.Description = Convert.ToString(read["Description"]);
                link.Displayorder = Convert.ToInt32(read["Displayorder"]);
                link.Status = Convert.ToInt32(read["Status"]);
                link.CreateDate = Convert.ToDateTime(read["CreateDate"]);

                list.Add(link);
            }
            read.Close();
            return list;
        }
Ejemplo n.º 47
0
        public ActionResult RsvpLinkSg(string id, string message, bool? confirm, FormCollection formCollection, bool regrets = false)
        {
            var li = new LinkInfo(rsvplinkSTR, landingSTR, id, false);
            if (li.error.HasValue())
                return Message(li.error);

            try
            {
                if (!li.pid.HasValue)
                    throw new Exception("missing peopleid");

                var meetingid = li.a[0].ToInt();
                var emailid = li.a[2].ToInt();
                var smallgroup = li.a[3];
                if (meetingid == 0 && li.a[0].EndsWith(".next"))
                {
                    var orgid = li.a[0].Split('.')[0].ToInt();
                    var nextmeet = (from mm in DbUtil.Db.Meetings
                                    where mm.OrganizationId == orgid
                                    where mm.MeetingDate > DateTime.Now
                                    orderby mm.MeetingDate
                                    select mm).FirstOrDefault();
                    if (nextmeet == null)
                        return Message("no meeting");
                    meetingid = nextmeet.MeetingId;
                }
                var q = (from pp in DbUtil.Db.People
                         where pp.PeopleId == li.pid
                         let meeting = DbUtil.Db.Meetings.SingleOrDefault(mm => mm.MeetingId == meetingid)
                         let org = meeting.Organization
                         select new {p = pp, org, meeting}).Single();

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                    throw new Exception("sorry, registration has been closed");

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                    throw new Exception("rsvp is no longer available");

                if (q.org.Limit <= q.meeting.Attends.Count(aa => aa.Commitment == 1))
                    throw new Exception("sorry, maximum limit has been reached");
                var omb = OrganizationMember.InsertOrgMembers(DbUtil.Db,
                    q.meeting.OrganizationId, li.pid.Value, MemberTypeCode.Member, DateTime.Now, null, false);
                if (smallgroup.HasValue())
                    omb.AddToGroup(DbUtil.Db, smallgroup);

                li.ot.Used = true;
                DbUtil.Db.SubmitChanges();
                Attend.MarkRegistered(DbUtil.Db, li.pid.Value, meetingid, regrets ? AttendCommitmentCode.Regrets : AttendCommitmentCode.Attending);
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}: {regrets}", q.org.OrganizationId, li.pid);
                var setting = DbUtil.Db.CreateRegistrationSettings(q.meeting.OrganizationId);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(DbUtil.Db, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", q.meeting.MeetingDate.ToString2("f"));
                    var NotifyIds = DbUtil.Db.StaffPeopleForOrg(q.org.OrganizationId);

                    DbUtil.Db.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    DbUtil.Db.Email(q.p.FromEmail, NotifyIds,
                        q.org.OrganizationName,
                        $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{q.meeting.MeetingDate.ToString2("f")}");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}Error: {regrets}", peopleid: li.pid);
                return Message(ex.Message);
            }
            return Message(message);
        }
Ejemplo n.º 48
0
 /// <summary>
 /// update link
 /// </summary>
 /// <param name="link"></param>
 /// <returns></returns>
 public int Update(LinkInfo link)
 {
     string cmdText = string.Format(@"update [{0}links] set
                         [type]=@type,
                         [linkname]=@linkname,
                         [linkurl]=@linkurl,
                         [position]=@position,
                         [target]=@target,
                         [description]=@description,
                         [sortnum]=@sortnum,
                         [status]=@status,
                         [createtime]=@createtime
                         where linkid=@linkid", ConfigHelper.Tableprefix);
     using (var conn = new DapperHelper().OpenConnection())
     {
        return conn.Execute(cmdText, new
         {
             Type = link.Type,
             LinkName = link.LinkName,
             LinkUrl = link.LinkUrl,
             Postion = link.Position,
             Target = link.Target,
             Description = link.Description,
             SortNum = link.SortNum,
             Status = link.Status,
             CreateTime = link.CreateTime,
             Linkid = link.LinkId
         });
     }
 }
Ejemplo n.º 49
0
        public ActionResult SendLink(string id, FormCollection formCollection)
        {
            var li = new LinkInfo(sendlinkSTR, landingSTR, id);
            if (li.error.HasValue())
                return Message(li.error);

            try
            {
                if (!li.pid.HasValue)
                    throw new Exception("missing peopleid");

                if (!li.oid.HasValue)
                    throw new Exception("missing orgid");

                var queueid = li.a[2].ToInt();
                var linktype = li.a[3]; // for supportlink, this will also have the goerid
                var q = (from pp in DbUtil.Db.People
                         where pp.PeopleId == li.pid
                         let org = DbUtil.Db.LoadOrganizationById(li.oid)
                         select new {p = pp, org}).Single();

                if (q.org == null && DbUtil.Db.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in DbUtil.Db.People
                         where pp.PeopleId == li.pid
                         let org = DbUtil.Db.LoadOrganizationById(oid)
                         select new {p = pp, org}).Single();
                }

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                    throw new Exception("sorry, registration has been closed");

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                    throw new Exception("sorry, registration is no longer available");

                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}", li.oid, li.pid);

                var expires = DateTime.Now.AddMinutes(DbUtil.Db.Setting("SendlinkExpireMintues", "30").ToInt());
                var c = DbUtil.Content("SendLinkMessage");
                if (c == null)
                {
                    c = new Content
                    {
                        Name = "SendLinkMessage",
                        Title = "Your Link for {org}",
                        Body = @"
            <p>Here is your temporary <a href='{url}'>LINK</a> to register for {org}.</p>

            <p>This link will expire at {time} (30 minutes).
            You may request another link by clicking the link in the original email you received.</p>

            <p>Note: If you did not request this link, please ignore this email,
            or contact the church if you need help.</p>
            "
                    };
                    DbUtil.Db.Contents.InsertOnSubmit(c);
                    DbUtil.Db.SubmitChanges();
                }
                var url = EmailReplacements.RegisterLinkUrl(DbUtil.Db,
                    li.oid.Value, li.pid.Value, queueid, linktype, expires);
                var subject = c.Title.Replace("{org}", q.org.OrganizationName);
                var msg = c.Body.Replace("{org}", q.org.OrganizationName)
                    .Replace("{time}", expires.ToString("f"))
                    .Replace("{url}", url)
                    .Replace("%7Burl%7D", url);

                var NotifyIds = DbUtil.Db.StaffPeopleForOrg(q.org.OrganizationId);
                DbUtil.Db.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation

                return Message($"Thank you, {q.p.PreferredName}, we just sent an email to {Util.ObscureEmail(q.p.EmailAddress)} with your link...");
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return Message(ex.Message);
            }
        }
Ejemplo n.º 50
0
 /// <summary>
 /// 添加
 /// </summary>
 /// <param name="link"></param>
 /// <returns></returns>
 public int InsertLink(LinkInfo link)
 {
     link.LinkId = _linkRepository.Insert(link);
     return(link.LinkId);
 }
Ejemplo n.º 51
0
        public ActionResult RegisterLink(string id, bool? showfamily, string source)
        {
            var li = new LinkInfo(registerlinkSTR, landingSTR, id);
            if (li.error.HasValue())
                return Message(li.error);

            try
            {
                if (!li.pid.HasValue)
                    throw new Exception("missing peopleid");

                if (!li.oid.HasValue)
                    throw new Exception("missing orgid");

                var linktype = li.a.Length > 3 ? li.a[3].Split(':') : "".Split(':');
                int? gsid = null;
                if (linktype[0].Equal("supportlink"))
                    gsid = linktype.Length > 1 ? linktype[1].ToInt() : 0;

                var q = (from pp in DbUtil.Db.People
                         where pp.PeopleId == li.pid
                         let org = DbUtil.Db.Organizations.SingleOrDefault(oo => oo.OrganizationId == li.oid)
                         let om = DbUtil.Db.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == li.oid && oo.PeopleId == li.pid)
                         select new {p = pp, org, om}).Single();

                if (q.org == null && DbUtil.Db.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in DbUtil.Db.People
                         where pp.PeopleId == li.pid
                         let org = DbUtil.Db.Organizations.SingleOrDefault(oo => oo.OrganizationId == oid)
                         let om = DbUtil.Db.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == oid && oo.PeopleId == li.pid)
                         select new {p = pp, org, om}).Single();
                }

                if (q.org == null)
                    throw new Exception("org missing, bad link");

                if (q.om == null && !gsid.HasValue && q.org.Limit <= q.org.RegLimitCount(DbUtil.Db))
                    throw new Exception("sorry, maximum limit has been reached");

                if (q.om == null && (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive))
                    throw new Exception("sorry, registration has been closed");

                DbUtil.LogActivity($"{registerlinkSTR}{landingSTR}", li.oid, li.pid);

                var url = string.IsNullOrWhiteSpace(source)
                    ? $"/OnlineReg/{li.oid}?registertag={id}"
                    : $"/OnlineReg/{li.oid}?registertag={id}&source={source}";
                if (gsid.HasValue)
                    url += "&gsid=" + gsid;
                if (showfamily == true)
                    url += "&showfamily=true";
                return Redirect(url);
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{registerlinkSTR}{landingSTR}Error: {ex.Message}", li.oid, li.pid);
                return Message(ex.Message);
            }
        }
Ejemplo n.º 52
0
 /// <summary>
 /// 修改
 /// </summary>
 /// <param name="link"></param>
 /// <returns></returns>
 public int UpdateLink(LinkInfo link)
 {
     return(_linkRepository.Update(link));
 }
 private void ActiveValueLinkHandle_OnAddLinkInfo(LinkInfo linkInfo)
 {
     ActiveValueTextBlock.Visibility = Visibility.Collapsed;
 }
Ejemplo n.º 54
0
        }                                                                // Optional

        public LinkInfoHandler(LinkInfo item)
        {
            Item = item;
        }
Ejemplo n.º 55
0
        public LinkInfo SetUpContext(PanelPreferences preferences, string skinFolderPath)
        {
            // Offline and Advanced mode Changes by Optimus

            var linkInfo = new LinkInfo { FolderName = Res.FolderName };
            if (!preferences.OfflineMode)
            {
                Login(preferences);

                try
                {
                    OpenPanelSettings(preferences);

                    var collection = new ContextCollection(CookieJar.SourceCode);

                    ContextInfo contextInfo = collection.FindAvailableContext();
                    Environment = contextInfo.Environment;

                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "OpenPortalSkinFolder", contextInfo.FolderName());
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "PortalSkinPath", Res.PortalSkinPathParent + "/" + contextInfo.FolderName() + "/");
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "IsHidden", "False");
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "Name", preferences.CompanyName + " Portal");

                    // Added for Language selection by Optimus
                    collection.UpdateFormValue(contextInfo.ContextIndex, -1, "Culture", preferences.Language);

                    PanelSettingsManagement.PanelSettingsUpdatePost(collection, preferences);
                    linkInfo.FolderName = contextInfo.FolderName();
                    linkInfo.PortalLink = contextInfo.OpenPortalTestBaseUrl; //TODO CHANGE TO LIVE LINK
                }
                catch (Exception e)
                {
                    // attempt to Navigate away to attempt not to lock panel settings
                    try
                    {
                        PanelSettingsManagement.PanelSettingsPostToHome(preferences);
                    }
                    catch (Exception) { }
                    throw e;
                }
            }
            return linkInfo;
        }
Ejemplo n.º 56
0
        public static LinkInfo GetSingleUrlFromUrlPicker(UrlPicker link)
        {
            LinkInfo linkInfo = null;

            if (link != null && link.Url != null)
            {
                if (link.Type == UrlPicker.UrlPickerTypes.Media)
                {
                    linkInfo          = new LinkInfo();
                    linkInfo.LinkType = UrlPicker.UrlPickerTypes.Media;

                    linkInfo.LinkUmbracoNode = link.TypeData.Media;

                    linkInfo.LinkURL = link.Url;

                    if (link.Meta.NewWindow)
                    {
                        linkInfo.LinkTitle  = " title=\"" + umbraco.library.GetDictionaryItem("USN New Window Title Tag") + "\" ";
                        linkInfo.LinkTarget = "target=\"_blank\"";
                        linkInfo.LinkIcon   = "<i class=\"ion-android-open after\"></i>";
                    }

                    if (link.Meta.Title == String.Empty)
                    {
                        linkInfo.LinkCaption = link.TypeData.Media.Name;
                    }
                    else
                    {
                        linkInfo.LinkCaption = link.Meta.Title;
                    }
                }
                else if (link.Type == UrlPicker.UrlPickerTypes.Content)
                {
                    linkInfo = new LinkInfo();

                    linkInfo.LinkUmbracoNode = link.TypeData.Content;
                    linkInfo.LinkType        = UrlPicker.UrlPickerTypes.Content;

                    linkInfo.LinkURL = link.Url;

                    if (link.Meta.NewWindow)
                    {
                        linkInfo.LinkTitle  = " title=\"" + umbraco.library.GetDictionaryItem("USN New Window Title Tag") + "\" ";
                        linkInfo.LinkTarget = "target=\"_blank\"";
                        linkInfo.LinkIcon   = "<i class=\"ion-android-open after\"></i>";
                    }

                    if (link.Meta.Title == String.Empty)
                    {
                        linkInfo.LinkCaption = link.TypeData.Content.Name;
                    }
                    else
                    {
                        linkInfo.LinkCaption = link.Meta.Title;
                    }

                    //Document types ending _AN should be linked to anchor position on page.
                    if (link.TypeData.Content.DocumentTypeAlias.IndexOf("_AN") != -1)
                    {
                        var    pageComponentsNode = link.TypeData.Content.Parent;
                        var    parentNode         = pageComponentsNode.Parent;
                        string anchor             = "#pos_" + link.TypeData.Content.Id.ToString();
                        linkInfo.LinkURL = parentNode.Url + anchor;
                    }
                }
                else if (link.Type == UrlPicker.UrlPickerTypes.Url)
                {
                    linkInfo = new LinkInfo();

                    linkInfo.LinkUmbracoNode = null;
                    linkInfo.LinkType        = UrlPicker.UrlPickerTypes.Url;

                    linkInfo.LinkURL = link.Url;

                    if (link.Meta.NewWindow)
                    {
                        linkInfo.LinkTitle  = " title=\"" + umbraco.library.GetDictionaryItem("USN New Window Title Tag") + "\" ";
                        linkInfo.LinkTarget = "target=\"_blank\"";
                        linkInfo.LinkIcon   = "<i class=\"ion-android-open after\"></i>";
                    }

                    if (link.Meta.Title == String.Empty)
                    {
                        linkInfo.LinkCaption = link.Url;
                    }
                    else
                    {
                        linkInfo.LinkCaption = link.Meta.Title;
                    }
                }
            }

            return(linkInfo);
        }
Ejemplo n.º 57
0
        public bool UpdateDraftingViews(ModelInfo sourceInfo, ModelInfo recipientInfo, TreeView treeViewSource, TreeView treeViewRecipient, bool createSheet, bool createLinks, TextBlock statusLable, ProgressBar progressBar)
        {
            bool result = false;

            try
            {
                List <int>        sourceViewIds  = new List <int>();
                List <PreviewMap> previewMapList = new List <PreviewMap>();

                ViewMapClass vmc = new ViewMapClass(sourceInfo, recipientInfo, createLinks);
                Dictionary <int, ViewProperties> sourceViews    = vmc.SourceViews;
                Dictionary <int, ViewProperties> recipientViews = vmc.RecipientViews;

                List <TreeViewModel> treeviewModels = treeViewSource.ItemsSource as List <TreeViewModel>;
                foreach (TreeViewModel rootNode in treeviewModels)
                {
                    foreach (TreeViewModel secondNode in rootNode.Children)
                    {
                        foreach (TreeViewModel viewNode in secondNode.Children)
                        {
                            if (viewNode.IsChecked == true)
                            {
                                int viewId = 0;
                                if (int.TryParse(viewNode.Tag.ToString(), out viewId))
                                {
                                    if (sourceViews.ContainsKey(viewId) && !sourceViewIds.Contains(viewId))
                                    {
                                        ViewProperties viewSource = sourceViews[viewId];
                                        if (viewSource.DependantViews.Count > 0)
                                        {
                                            foreach (int dependentId in viewSource.DependantViews.Keys)
                                            {
                                                if (!sourceViewIds.Contains(dependentId))
                                                {
                                                    ViewProperties dependentSource    = viewSource.DependantViews[dependentId];
                                                    ViewProperties dependentRecipient = null;
                                                    LinkInfo       dependantlinkInfo  = new LinkInfo();
                                                    if (null != dependentSource.LinkedView)
                                                    {
                                                        dependentRecipient = dependentSource.LinkedView;
                                                        var linkInfoList = from info in vmc.LinkInfoList where info.SourceItemId == dependentId && info.DestItemId == dependentRecipient.ViewId select info;
                                                        if (linkInfoList.Count() > 0)
                                                        {
                                                            dependantlinkInfo = linkInfoList.First();
                                                        }
                                                    }

                                                    PreviewMap dependantView = new PreviewMap();
                                                    dependantView.SourceModelInfo         = sourceInfo;
                                                    dependantView.RecipientModelInfo      = recipientInfo;
                                                    dependantView.SourceViewProperties    = dependentSource;
                                                    dependantView.RecipientViewProperties = dependentRecipient;
                                                    dependantView.ViewLinkInfo            = dependantlinkInfo;
                                                    dependantView.IsEnabled = true;

                                                    sourceViewIds.Add(dependentId);
                                                    previewMapList.Add(dependantView);
                                                }
                                            }
                                        }

                                        ViewProperties viewRecipient = null;
                                        LinkInfo       linkInfo      = new LinkInfo();
                                        if (null != viewSource.LinkedView)
                                        {
                                            viewRecipient = viewSource.LinkedView;
                                            var linkInfoList = from info in vmc.LinkInfoList where info.SourceItemId == viewId && info.DestItemId == viewRecipient.ViewId && info.ItemStatus != LinkItemStatus.Deleted select info;
                                            if (linkInfoList.Count() > 0)
                                            {
                                                linkInfo = linkInfoList.First();
                                            }
                                        }

                                        PreviewMap preview = new PreviewMap();
                                        preview.SourceModelInfo         = sourceInfo;
                                        preview.RecipientModelInfo      = recipientInfo;
                                        preview.SourceViewProperties    = viewSource;
                                        preview.RecipientViewProperties = viewRecipient;
                                        preview.ViewLinkInfo            = linkInfo;
                                        preview.IsEnabled = true;

                                        sourceViewIds.Add(viewId);
                                        previewMapList.Add(preview);
                                    }
                                }
                            }
                        }
                    }
                }

                if (previewMapList.Count > 0)
                {
                    PreviewWindow pWindow = new PreviewWindow(previewMapList, createSheet);
                    if (true == pWindow.ShowDialog())
                    {
                        previewMapList = pWindow.PreviewMapList;

                        progressBar.Visibility = System.Windows.Visibility.Visible;
                        statusLable.Visibility = System.Windows.Visibility.Visible;

                        bool updatedDictionary  = UpdateRecipientViewDictionary(recipientInfo, previewMapList);
                        bool updatedGoogleSheet = GoogleSheetUtil.WriteLinkIfo(recipientInfo.GoogleSheetID, recipientInfo.LinkInfoCollection);
                        bool updatedLinkStatus  = UpdateLinkStatus(recipientInfo);

                        progressBar.Visibility = System.Windows.Visibility.Hidden;
                        statusLable.Visibility = System.Windows.Visibility.Hidden;
                    }
                }
                else
                {
                    MessageBox.Show("Please select at least one source item to duplicate views.", "Select a Source Item", MessageBoxButton.OK, MessageBoxImage.Information);
                    result = false;
                }
                result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to update drafting views.\n" + ex.Message, "Update Drafting Views", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(result);
        }
Ejemplo n.º 58
0
        public static Func <object, JsonData[], HttpRequestMessage, HtmlResult <HElement> > HViewCreator(
            string kind, int?id)
        {
            return(delegate(object _state, JsonData[] jsons, HttpRequestMessage context)
            {
                SiteState state = _state as SiteState;
                if (state == null)
                {
                    state = new SiteState();
                }

                LinkInfo link = null;
                if (kind == "news" || kind == "user" || (kind == "novosti" && id != null) ||
                    kind == "article" || kind == "topic" || kind == "tags" || kind == "dialog" || kind == "confirmation")
                {
                    link = new LinkInfo("", kind, id);
                }
                else
                {
                    if (StringHlp.IsEmpty(kind))
                    {
                        link = new LinkInfo("", "", null);
                    }
                    else if (id == null)
                    {
                        link = store.Links.FindLink(kind, "");
                        if (link == null)
                        {
                            link = store.Links.FindLink("page", kind);
                        }
                    }
                }

                if (link == null)
                {
                    return new HtmlResult
                    {
                        RawResponse = new HttpResponseMessage()
                        {
                            StatusCode = HttpStatusCode.NotFound
                        }
                    };
                }

                if (jsons.Length > 0)
                {
                    state.AccessTime = DateTime.UtcNow;
                }

                foreach (JsonData json in jsons)
                {
                    try
                    {
                        if (state.IsRattling(json))
                        {
                            continue;
                        }

                        try
                        {
                            string command = json.JPath("data", "command")?.ToString();
                            if (command != null && StringHlp.IsEmpty(state.BlockHint))
                            {
                                if (command.StartsWith("save_"))
                                {
                                    object id1 = json.JPath("data", "id1");

                                    string hint = command.Substring(5);
                                    if (id != null)
                                    {
                                        hint = string.Format("{0}_{1}", hint, id1);
                                    }
                                    state.BlockHint = hint;

                                    Logger.AddMessage("Restore: {0}", hint);
                                }
                                else if (command == "tag_add" && kind == "")
                                {
                                    state.BlockHint = "news_add";

                                    Logger.AddMessage("Restore: news_add");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.WriteException(ex);
                        }

                        state.Operation.Reset();

                        HElement cachePage = Page(HttpContext.Current, state, link.Kind, link.Id);

                        hevent eventh = cachePage.FindEvent(json, true);
                        if (eventh != null)
                        {
                            eventh.Execute(json);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteException(ex);
                        state.Operation.Message = string.Format("Непредвиденная ошибка: {0}", ex.Message);
                    }
                }

                HElement page = Page(HttpContext.Current, state, link.Kind, link.Id);
                if (page == null)
                {
                    return new HtmlResult
                    {
                        RawResponse = new HttpResponseMessage()
                        {
                            StatusCode = HttpStatusCode.NotFound
                        }
                    };
                }
                return HtmlHlp.FirstHtmlResult(page, state, TimeSpan.FromHours(1));
            });
        }
Ejemplo n.º 59
0
        /// <summary>
        /// 转换实体
        /// </summary>
        /// <param LinkName="read">OleDbDataReader</param>
        /// <param name="read"></param>
        /// <returns>LinkInfo</returns>
        private static List<LinkInfo> DataReaderToListLink(OleDbDataReader read)
        {
            var list = new List<LinkInfo>();
            while (read.Read())
            {
                var link = new LinkInfo
                               {
                                   LinkId = Convert.ToInt32(read["Linkid"]),
                                   Type = Convert.ToInt32(read["Type"]),
                                   LinkName = Convert.ToString(read["LinkName"]),
                                   LinkUrl = Convert.ToString(read["LinkUrl"]),
                                   Target = Convert.ToString(read["Target"]),
                                   Description = Convert.ToString(read["Description"]),
                                   SortNum = Convert.ToInt32(read["SortNum"]),
                                   Status = Convert.ToInt32(read["Status"]),
                                   CreateTime = Convert.ToDateTime(read["CreateTime"])
                               };
                if (read["Position"] != DBNull.Value)
                {
                    link.Position = Convert.ToInt32(read["Position"]);
                }

                list.Add(link);
            }
            read.Close();
            return list;
        }
Ejemplo n.º 60
0
        private bool UpdateRecipientViewDictionary(ModelInfo recipientInfo, List <PreviewMap> mapList)
        {
            bool updated = false;

            try
            {
                //update link info
                ObservableCollection <LinkInfo>  linkInfoCollection = recipientInfo.LinkInfoCollection;
                Dictionary <int, ViewProperties> viewDictionary     = recipientInfo.ViewDictionary;
                foreach (PreviewMap map in mapList)
                {
                    LinkInfo info = map.ViewLinkInfo;
                    if (info.DestItemId == -1)
                    {
                        continue;
                    }                                        //skipped items
                    var foundLink = linkInfoCollection.Where(x => x.SourceModelId == info.SourceModelId && x.SourceItemId == info.SourceItemId);
                    if (foundLink.Count() > 0)
                    {
                        int index = linkInfoCollection.IndexOf(foundLink.First());
                        if (linkInfoCollection[index].ItemStatus == LinkItemStatus.None) //existing in the spreadsheet
                        {
                            linkInfoCollection[index]            = info;
                            linkInfoCollection[index].ItemStatus = LinkItemStatus.Updated;
                        }
                    }
                    else if (info.ItemStatus == LinkItemStatus.None)
                    {
                        info.ItemStatus = LinkItemStatus.Added;
                        linkInfoCollection.Add(info);
                    }

                    ViewProperties vp = map.RecipientViewProperties;
                    if (null != vp)
                    {
                        if (viewDictionary.ContainsKey(vp.ViewId))
                        {
                            viewDictionary.Remove(vp.ViewId);
                        }
                        viewDictionary.Add(vp.ViewId, vp);
                    }
                }

                //update dictionary
                recipientInfo.LinkInfoCollection = linkInfoCollection;
                recipientInfo.ViewDictionary     = viewDictionary;

                if (modelInfoDictionary.ContainsKey(recipientInfo.RevitDocumentID))
                {
                    modelInfoDictionary.Remove(recipientInfo.RevitDocumentID);
                }

                modelInfoDictionary.Add(recipientInfo.RevitDocumentID, recipientInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to update the recipient model info.\n" + ex.Message, "Update Recipient Model Info", MessageBoxButton.OK, MessageBoxImage.Warning);
                updated = false;
            }
            return(updated);
        }