Example #1
0
    public void OnCameraMove()
    {
        //StopAllCoroutines();

        Hashtable hash = new Hashtable();
        hash.Add("position", TargetPos);
        hash.Add("time", MovingSec);
        hash.Add("easetype", iTween.EaseType.easeInOutExpo);
        iTween.MoveTo(gameObject, hash);

        hash.Clear();
        hash.Add("rotation", TargetAngle);
        hash.Add("time", MovingSec);
        hash.Add("easetype", iTween.EaseType.easeInOutExpo);
        iTween.RotateTo(gameObject, hash);

        hash.Clear();
        hash.Add("from", CameraObject.orthographicSize);
        hash.Add("to", TargetSize);
        hash.Add("time", MovingSec);
        hash.Add("onupdate", "SizeUpdate");
        hash.Add("easetype", iTween.EaseType.easeInOutExpo);
        iTween.ValueTo(gameObject, hash);

    }
Example #2
0
    /// <summary>
    /// 从左到右移动
    /// </summary>
    /// <param name="time">Time.</param>
    protected override IEnumerator MoveLeftRight()
    {
        //Vector3 pos1 = new Vector3 (go.transform.position.x, go.transform.position.y + 0.3f, go.transform.position.z);
        Hashtable args = new Hashtable ();

        Transform layer3 = GetTransform (gameObject.transform, "layer3");
        GameObject go = layer3.gameObject;

        Vector3 origin2 = go.transform.position;
        Vector3 pos2 = new Vector3 (go.transform.position.x - 0.3f, go.transform.position.y, go.transform.position.z);

        args.Clear ();
        args.Add ("time", 1.5f);
        args.Add ("position", pos2);
        args.Add ("easetype", "linear");
        iTween.MoveTo (go, args);

        yield return new WaitForSeconds (1.5f);
        //Vector3 pos1 = new Vector3 (go.transform.position.x - 0.5f, go.transform.position.y, go.transform.position.z);

        args.Clear ();

        args.Add ("time", 1.5f);
        args.Add ("position", origin2);
        args.Add ("easetype", "linear");

        iTween.MoveTo (go, args);

        yield return new WaitForSeconds (1.5f);
        Vector3 pos1 = new Vector3 (go.transform.position.x + 0.3f, go.transform.position.y, go.transform.position.z);

        args.Clear ();

        args.Add ("time", 1.5f);
        args.Add ("position", pos1);
        args.Add ("easetype", "linear");

        iTween.MoveTo (go, args);

        yield return new WaitForSeconds (1.5f);

        args.Clear ();

        args.Add ("time", 1.5f);
        args.Add ("position", origin2);
        args.Add ("easetype", "linear");

        iTween.MoveTo (go, args);

        yield return new WaitForSeconds (1.5f);

        Move2();
    }
Example #3
0
        public void TestClearBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);
            Hashtable ht1 = null;
            string s1 = null;
            string s2 = null;

            int i = 0;
            ht1 = new Hashtable(); //default constructor
            ht1.Clear();

            Assert.Equal(0, ht1.Count);

            // add 100 key-val pairs
            ht1 = new Hashtable();

            for (i = 0; i < 100; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                ht1.Add(s1, s2);
            }

            Assert.Equal(100, ht1.Count);
            ht1.Clear();

            Assert.Equal(0, ht1.Count);

            //[]we will make a token call for some important methods to make sure that this is indeed clear
            s1 = "key_0";
            Assert.False(ht1.ContainsKey(s1));

            s1 = "val_0";
            Assert.False(ht1.ContainsValue(s1));

            //[]repeated clears of the HT. Nothing should happen		

            for (i = 0; i < 100; i++)
            {
                ht1.Clear();

                Assert.Equal(0, ht1.Count);
            }
        }
Example #4
0
 protected void ImageButtonGiant_Click(object sender, ImageClickEventArgs e)
 {
     //����һ����ϣ��ht
     Hashtable ht = new Hashtable();
     string where = "";
     //Ӧ��foreachѭ��GridView�ؼ��е�CheckBox�ؼ�
     foreach (GridViewRow row in GV.Rows)
     {
         //������¹�ϣ���е�����
         ht.Clear();
         //Ӧ��FindControl��������GridView�ؼ���CheckBox�ؼ�,���ж��Ƿ�ѡ�������û�Ȩ��
         ht.Add("HasDuty_DepartmentManage", ((CheckBox)row.FindControl("chkDepartmentManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_UserManage", ((CheckBox)row.FindControl("chkUserManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_RoleManage", ((CheckBox)row.FindControl("chkUserManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_Role", ((CheckBox)row.FindControl("chkUserManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_CourseManage", ((CheckBox)row.FindControl("chkCourseManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_PaperSetup", ((CheckBox)row.FindControl("chkPaperSetup")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_PaperLists", ((CheckBox)row.FindControl("chkPaperSetup")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_UserPaperList", ((CheckBox)row.FindControl("chkUserPaperList")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_UserScore", ((CheckBox)row.FindControl("chkUserPaperList")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_SingleSelectManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_MultiSelectManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_FillBlankManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_JudgeManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
         ht.Add("HasDuty_QuestionManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
         //����һ����ѯ���������
         where = " Where RoleId=" + row.Cells[0].Text;
         //����Rolemr�������е�Update�����޸Ľ�ɫȨ����Ϣ
         Rolemr.Update(ht, where);
     }
 }
    protected void ImageButtonGiant_Click(object sender, ImageClickEventArgs e)
    {
        Hashtable ht = new Hashtable();
        string where = "";

        foreach (GridViewRow row in GridView1.Rows)
        {
            ht.Clear();
            ht.Add("HasDuty_UserManage", ((CheckBox)row.FindControl("chkUserManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_RoleManage", ((CheckBox)row.FindControl("chkUserManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_Role", ((CheckBox)row.FindControl("chkUserManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_CourseManage", ((CheckBox)row.FindControl("chkCourseManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_PaperSetup", ((CheckBox)row.FindControl("chkPaperSetup")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_PaperLists", ((CheckBox)row.FindControl("chkPaperSetup")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_UserPaperList", ((CheckBox)row.FindControl("chkUserPaperList")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_UserScore", ((CheckBox)row.FindControl("chkUserPaperList")).Checked == true ? 1 : 0);

            ht.Add("HasDuty_SingleSelectManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_MultiSelectManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_FillBlankManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_JudgeManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);
            ht.Add("HasDuty_QuestionManage", ((CheckBox)row.FindControl("chkTypeManage")).Checked == true ? 1 : 0);

            where = " Where RoleId=" + row.Cells[0].Text;
            Role.Update(ht, where);
        }
        Page.RegisterStartupScript("", "<script>alert('授权成功!');</script>");
    }
Example #6
0
        public void TestCtorDictionarySingle()
        {
            // No exception
            var hash = new Hashtable(new Hashtable(), 1f);
            // No exception
            hash = new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()), 1f), 1f), 1f), 1f);

            // []test to see if elements really get copied from old dictionary to new hashtable
            Hashtable tempHash = new Hashtable();
            // this for assumes that MinValue is a negative!
            for (long i = long.MinValue; i < long.MinValue + 100; i++)
            {
                tempHash.Add(i, i);
            }

            hash = new Hashtable(tempHash, 1f);

            // make sure that new hashtable has the elements in it that old hashtable had
            for (long i = long.MinValue; i < long.MinValue + 100; i++)
            {
                Assert.True(hash.ContainsKey(i));
                Assert.True(hash.ContainsValue(i));
            }

            //[]make sure that there are no connections with the old and the new hashtable
            tempHash.Clear();
            for (long i = long.MinValue; i < long.MinValue + 100; i++)
            {
                Assert.True(hash.ContainsKey(i));
                Assert.True(hash.ContainsValue(i));
            }
        }
Example #7
0
 /// <devdoc>
 /// Clears all elements in the table.
 /// </devdoc>
 public void Clear()
 {
     if (_readOnly)
     {
         throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
     }
     _objectsTable?.Clear();
     _objectsArray?.Clear();
 }
Example #8
0
	public static void Main (string [] args)
	{
		Hashtable ht = new Hashtable ();
		Assembly asm = Assembly.GetAssembly (typeof (test));
		foreach (Type t in asm.GetTypes ()) {
			ht.Clear ();
			foreach (FieldInfo fi in t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
				ht.Add (fi.Name, fi);
		}
	}
    public static SortedDictionary<int, string> yt(string targetUri)
    {
        CookieContainer cc = new CookieContainer();
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(targetUri);
        req.CookieContainer = cc;
        req.Timeout = 5000;
        req.GetResponse().Close();
        req = (HttpWebRequest)WebRequest.Create("http://www.youtube.com/get_video_info?video_id=" + Regex.Match(targetUri, "(?<=v=)[\\w-]+").Value);
        req.CookieContainer = cc;
        string _info = null;
        System.Net.WebResponse res = req.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream());
        _info = sr.ReadToEnd();
        sr.Close();
        res.Close();
        Hashtable info = new Hashtable();
        Dictionary<string, string> _tmp = new Dictionary<string, string>();
        SortedDictionary<int, string> fmtmap = new SortedDictionary<int, string>();

        foreach (string item in _info.Split('&'))
        {
            info.Add(item.Split('=')[0], Uri.UnescapeDataString(item.Split('=')[1]));
        }
        if (Convert.ToString(info["status"]) == "fail")
        {
            throw new UnauthorizedAccessException();
        }
        foreach (string item in Convert.ToString(info["url_encoded_fmt_stream_map"]).Split(','))
        {
            foreach (string a in item.Split('&'))
            {
                _tmp.Add(a.Split('=')[0], Uri.UnescapeDataString(a.Split('=')[1]));
            }
            fmtmap.Add(Convert.ToInt32(_tmp["itag"]), (_tmp["url"]) + "&signature=");
            _tmp.Clear();
        }

        req = (HttpWebRequest)WebRequest.Create("http://www.youtube.com/get_video_info?video_id=" + Regex.Match(targetUri, "(?<=v=)\\w+").Value + "&t=" + Convert.ToString(info["token"]));
        req.CookieContainer = cc;
        req.Timeout = 1500;
        req.GetResponse().Close();

        fmtmap[-2] = Convert.ToString(info["title"]);
        fmtmap[-1] = cc.GetCookieHeader(new Uri("http://www.youtube.com"));
        info.Clear();
        return fmtmap;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check permissions for CMS Desk -> Tools
        CurrentUserInfo user = CMSContext.CurrentUser;
        if (!user.IsAuthorizedPerUIElement("CMS.Desk", "Tools"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Desk", "Tools");
        }

        // Check permissions for CMS Desk -> Tools -> BizForms
        if (!user.IsAuthorizedPerUIElement("CMS.Tools", "Form"))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.Tools", "Form");
        }

        // Check 'ReadData' permission
        if (!user.IsAuthorizedPerResource("cms.form", "ReadData"))
        {
            RedirectToCMSDeskAccessDenied("cms.form", "ReadData");
        }

        // Get form id from url
        formId = QueryHelper.GetInteger("formid", 0);

        BizFormInfo bfi = BizFormInfoProvider.GetBizFormInfo(formId);
        EditedObject = bfi;

        if (bfi != null)
        {
            // Check authorized roles for this form
            if (!bfi.IsFormAllowedForUser(CMSContext.CurrentUser.UserName, CMSContext.CurrentSiteName))
            {
                RedirectToAccessDenied(GetString("Bizforms.FormNotAllowedForUserRoles"));
            }
        }

        string[] columnNames = null;
        DataClassInfo dci = null;
        Hashtable reportFields = new Hashtable();
        FormInfo fi = null;

        // Initialize controls
        this.CurrentMaster.Title.TitleText = GetString("BizForm_Edit_Data_SelectFields.Title");
        this.CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Form/selectfields.png");
        this.CurrentMaster.DisplayActionsPanel = true;

        btnSelectAll.Text = GetString("BizForm_Edit_Data_SelectFields.SelectAll");

        if (!RequestHelper.IsPostBack())
        {
            btnOk.Text = GetString("General.OK");
            btnCancel.Text = GetString("General.Cancel");

            if (bfi != null)
            {
                // Get dataclass info
                dci = DataClassInfoProvider.GetDataClass(bfi.FormClassID);

                if (dci != null)
                {
                    // Get columns names
                    fi = FormHelper.GetFormInfo(dci.ClassName, false);

                    columnNames = fi.GetColumnNames();
                }

                // Get report fields
                if (String.IsNullOrEmpty(bfi.FormReportFields))
                {
                    reportFields = LoadReportFields(columnNames);
                }
                else
                {
                    reportFields.Clear();

                    foreach (string field in bfi.FormReportFields.Split(';'))
                    {
                        // Add field key to hastable
                        reportFields[field] = null;
                    }
                }

                if (columnNames != null)
                {
                    foreach (string name in columnNames)
                    {
                        FormFieldInfo ffi = fi.GetFormField(name);

                        // Add checkboxes to the list
                        ListItem item = new ListItem(ResHelper.LocalizeString(GetFieldCaption(ffi, name)), name);
                        if (reportFields.Contains(name))
                        {
                            // Select checkbox if field is reported
                            item.Selected = true;
                        }
                        chkListFields.Items.Add(item);
                    }
                }
            }
        }
    }
Example #11
0
        public void TestRemove02()
        {
            Hashtable hash = null;

            int ii;

            #region "Test Data"
            string[] strSuperHeroes = new string[]
            {
                "Captain Marvel" ,      //0
                "Batgirl" ,             //1
                "Nightwing" ,           //2
                "Green Lantern" ,       //3
                "Robin" ,               //4
                "Superman" ,            //5
                "Black Canary" ,        //6
                "Spiderman" ,           //7
                "Iron Man" ,            //8
                "Wonder Girl" ,        //9
                "Batman" ,              //10
                "Flash" ,               //11
                "Green Arrow" ,        //12
                "Atom" ,                //13
                "Steel" ,               //14
                "Powerman" ,            //15
            };

            string[] strSecretIdentities = new string[]
            {
                "Batson, Billy" ,       //0
                "Gordan, Barbara" ,     //1
                "Grayson, Dick" ,       //2
                "Jordan, Hal" ,     //3
                "Drake, Tim" ,          //4
                "Kent, Clark" ,     //5
                "Lance, Dinah" ,        //6
                "Parker, Peter" ,       //7
                "Stark, Tony" ,     //8
                "Troy, Donna" ,     //9
                "Wayne, Bruce" ,        //10
                "West, Wally" ,     //11
                "Queen, Oliver" ,       //12
                "Palmer, Ray" ,     //13
                "Irons, John Henry" ,   //14
                "Cage, Luke" ,          //15
            };
            #endregion

            // Allocate the hash table.
            hash = new Hashtable();

            // Construct the hash table by adding items to the table.
            for (ii = 0; ii < strSuperHeroes.Length; ++ii)
            {
                hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
            }

            // Validate additions to Hashtable.
            Assert.Equal(strSuperHeroes.Length, hash.Count);

            //
            // []Remove: Attempt to remove a bogus key entry from table.
            //
            hash.Remove("THIS IS A BOGUS KEY");
            Assert.Equal(hash.Count, strSuperHeroes.Length);

            //
            // []	Remove: Attempt to remove a null key entry from table.
            //
            Assert.Throws<ArgumentNullException>(() =>
            {
                hash.Remove(null);
            }
            );

            //
            // [] Remove: Add key/value pair to Hashtable and remove items.
            //
            // Remove items from Hashtable.
            for (ii = 0; ii < strSuperHeroes.Length; ++ii)
            {
                hash.Remove(strSuperHeroes[ii]);
                Assert.Equal(strSuperHeroes.Length - ii - 1, hash.Count);
            }


            // now ADD ALL THE Entries the second time and remove them again
            for (ii = 0; ii < strSuperHeroes.Length; ++ii)
            {
                hash.Add(strSuperHeroes[ii], strSecretIdentities[ii]);
            }

            // remove elements
            for (ii = 0; ii < strSuperHeroes.Length; ++ii)
            {
                hash.Remove(strSuperHeroes[ii]);
                Assert.Equal(hash.Count, strSuperHeroes.Length - ii - 1);
            }

            //[]Repeated removed
            hash.Clear();
            for (int iAnnoying = 0; iAnnoying < 10; iAnnoying++)
            {
                for (ii = 0; ii < strSuperHeroes.Length; ++ii)
                {
                    hash.Remove(strSuperHeroes[ii]);
                    Assert.Equal(0, hash.Count);
                }
            }
        }
Example #12
0
        public void TestAddClearRepeatedly()
        {
            int inLoops0 = 2;
            int inLoops1 = 2;

            var ht2 = new Hashtable();
            for (int aa = 0; aa < inLoops0; aa++)
            {
                for (int bb = 0; bb < inLoops1; bb++)
                {
                    ht2.Add("KEY: aa==" + aa + " ,bb==" + bb, "VALUE: aa==" + aa + " ,bb==" + bb);
                }

                Assert.Equal(inLoops1, ht2.Count);
                ht2.Clear();
            }
        }
Example #13
0
 public Boolean runTest()
 {
     int iCountErrors = 0;
     int iCountTestcases = 0;
     Console.Out.Write( strPath );
     Console.Out.Write( strTest );
     Console.Out.WriteLine( " runTest() started..." );
     Hashtable hash = null;
     int ii;
     String[] strSuperHeroes = new String[]
     {
         "Captain Marvel" ,		
         "Batgirl" ,			
         "Nightwing" ,			
         "Green Lantern" ,		
         "Robin" ,				
         "Superman" ,			
         "Black Canary" ,		
         "Spiderman" ,			
         "Iron Man" ,			
         "Wonder Girl" ,		
         "Batman" ,				
         "Flash" ,				
         "Green Arrow" ,		
         "Atom" ,				
         "Steel" ,				
         "Powerman" ,			
     };
     String[] strSecretIdentities = new String[]
     {
         "Batson, Billy" ,		
         "Gordan, Barbara" ,	
         "Grayson, Dick" ,		
         "Jordan, Hal" ,		
         "Drake, Tim" ,			
         "Kent, Clark" ,		
         "Lance, Dinah" ,		
         "Parker, Peter" ,		
         "Stark, Tony" ,		
         "Troy, Donna" ,		
         "Wayne, Bruce" ,		
         "West, Wally" ,		
         "Queen, Oliver" ,		
         "Palmer, Ray" ,		
         "Irons, John Henry" ,	
         "Cage, Luke" ,			
     };
     hash = new Hashtable();
     for ( ii = 0; ii < strSuperHeroes.Length; ++ii )
     {
         iCountTestcases++;
         try
         {
             hash.Add( strSuperHeroes[ii], strSecretIdentities[ii] );
         }
         catch ( Exception ex )
         {
             Console.WriteLine( strTest, " E_101, unexpected exception when adding elements, exception = " +  ex.ToString() );
             ++iCountErrors;
         }
     }
     iCountTestcases++;
     if ( hash.Count != strSuperHeroes.Length )
     {
         Console.WriteLine( strTest, " E_202, hash.Count " + hash.Count.ToString() + " does not equal strSuperHeroes.Length " + strSuperHeroes.Length.ToString() );
         ++iCountErrors;
     }
     iCountTestcases++;
     Console.Out.WriteLine( "Remove: Attempt to remove a bogus key entry from table" );
     try
     {
         hash.Remove( "THIS IS A BOGUS KEY"  );
         if ( hash.Count != strSuperHeroes.Length )
         {
             Console.WriteLine( strTest, " E_303, hash.Count " + hash.Count.ToString() + " does not equal strSuperHeroes.Length " + strSuperHeroes.Length.ToString() );
             ++iCountErrors;
         }
     }
     catch ( Exception ex )
     {
         Console.WriteLine( strTest, " E_404, unexpected exception when removing bogus element, exception = " +  ex.ToString() );
         ++iCountErrors;
     }
     iCountTestcases++;
     Console.Out.WriteLine( "Remove: Attempt to remove a null key entry from table" );
     try
     {
         hash.Remove( null );
         Console.WriteLine( strTest, " E_505, expected ArgumentNullException but did not throw any exception ");
         ++iCountErrors;
     }
     catch ( ArgumentNullException )
     {
     }
     catch ( Exception ex )
     {
         Console.WriteLine( strTest, " E_606, throw unexpected exception, exception="+ex.ToString());
         ++iCountErrors;
     }
     Console.Out.WriteLine( "Remove: Add key/value pair to Hashtable and remove items" );
     for ( ii = 0; ii < strSuperHeroes.Length; ++ii )
     {
         iCountTestcases++;
         try
         {
             hash.Remove( strSuperHeroes[ii] );
             if ( hash.Count != strSuperHeroes.Length - ii - 1 )
             {
                 Console.WriteLine( strTest, " E_707, hash.Count " + hash.Count.ToString() + " does not equal strSuperHeroes.Length " + (strSuperHeroes.Length - ii - 1).ToString());
                 ++iCountErrors;
             }
         }
         catch ( Exception ex )
         {
             Console.WriteLine( strTest, " E_808, throw unexpected exception, exception="+ex.ToString());
             ++iCountErrors;
         }
     }
     for ( ii = 0; ii < strSuperHeroes.Length; ++ii )
     {
         iCountTestcases++;
         try
         {
             hash.Add( strSuperHeroes[ii], strSecretIdentities[ii] );
         }
         catch ( Exception ex )
         {
             Console.WriteLine( strTest, " E_909, unexpected exception when adding elements FOR SECOND TIME and removing them, exception = " +  ex.ToString() );
             ++iCountErrors;
         }
     }
     for ( ii = 0; ii < strSuperHeroes.Length; ++ii )
     {
         iCountTestcases++;
         try
         {
             hash.Remove( strSuperHeroes[ii] );
             if ( hash.Count != strSuperHeroes.Length - ii - 1 )
             {
                 Console.WriteLine( strTest, " E_111, hash.Count " + hash.Count.ToString() + " does not equal strSuperHeroes.Length " + (strSuperHeroes.Length - ii - 1).ToString());
                 ++iCountErrors;
             }
         }
         catch ( Exception ex )
         {
             Console.WriteLine( strTest, " E_222, unexpected exception when adding elements FOR SECOND TIME and removing them, exception = " +  ex.ToString() );
             ++iCountErrors;
         }
     }
     hash.Clear();
     for(int iAnnoying = 0; iAnnoying<10; iAnnoying++)
     {
         for ( ii = 0; ii < strSuperHeroes.Length; ++ii )
         {
             iCountTestcases++;
             try
             {
                 hash.Remove( strSuperHeroes[ii] );
                 if ( hash.Count != 0 )
                 {
                     Console.WriteLine( strTest, " E_6534sg, hash.Count ");
                     ++iCountErrors;
                 }
             }
             catch ( Exception ex )
             {
                 Console.WriteLine( strTest, " E_222, unexpected exception when adding elements FOR SECOND TIME and removing them, exception = " +  ex.ToString() );
                 ++iCountErrors;
             }
         }
     }
     Console.Error.Write( strName );
     Console.Error.Write( ": " );
     if ( iCountErrors == 0 )
     {
         Console.Error.Write( strTest );
         Console.Error.WriteLine( " paSs, iCountTestcases=="  + iCountTestcases);
         return true;
     }
     else
     {
         Console.Write( strTest + strPath );
         Console.WriteLine( strTest + "FAiL" );
         Console.Error.Write( strTest );
         Console.Error.Write( " iCountErrors==" );
         Console.Error.WriteLine( iCountErrors );
         return false;
     }
 }
Example #14
0
    protected void btn_PatternSelect_Click(object sender, EventArgs e)
    {
        #region
        try
        {
            ALOModel.MaintainPatternSpec BCO = new ALOModel.MaintainPatternSpec(ConnectionDB);
            Hashtable htTemp = new Hashtable();
            htTemp.Clear();
            htTemp.Add("ChanNo", SLP_StoreChain1.Text.Trim());
            htTemp.Add("Store", SLP_Store1.Text.Trim());
            htTemp.Add("StartDate", SLP_SLPDate2.Text.Trim());
            htTemp.Add("EndDate", SLP_SLPDate3.Text.Trim());

            if (CheckPATTERNSPECCanAdd(htTemp))
            {

                dtMultiSaveClassAndItem = dtClassAndItemSelected;

                if (dtMultiSaveClassAndItem.Rows.Count > 0)
                {

                    #region
                    if (!dtMultiSaveClassAndItem.Columns.Contains("chan_no"))
                        dtMultiSaveClassAndItem.Columns.Add("chan_no");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("store"))
                        dtMultiSaveClassAndItem.Columns.Add("store");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("SPEC_TYPE"))
                        dtMultiSaveClassAndItem.Columns.Add("SPEC_TYPE");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("SPEC_TYPE_NAME"))
                        dtMultiSaveClassAndItem.Columns.Add("SPEC_TYPE_NAME");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("S_START_DATE"))
                        dtMultiSaveClassAndItem.Columns.Add("S_START_DATE");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("S_END_DATE"))
                        dtMultiSaveClassAndItem.Columns.Add("S_END_DATE");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("spec_qty"))
                        dtMultiSaveClassAndItem.Columns.Add("spec_qty");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("reason"))
                        dtMultiSaveClassAndItem.Columns.Add("reason");
                    if (!dtMultiSaveClassAndItem.Columns.Contains("explain"))
                        dtMultiSaveClassAndItem.Columns.Add("explain");
                    #endregion

                    strErrMsgAfterChecked = "";//清空暫存錯誤訊息

                    //Add Data to Temp DataTable
                    for (Int32 i = dtMultiSaveClassAndItem.Rows.Count - 1; i >= 0; i--)
                    {
                        htTemp.Clear();
                        htTemp.Add("ChanNo", SLP_StoreChain1.Text.Trim());
                        htTemp.Add("Store", SLP_Store1.Text.Trim());
                        htTemp.Add("ROOT_NO", dtMultiSaveClassAndItem.Rows[i]["ROOT_NO"].ToString().Trim());
                        htTemp.Add("PMA", dtMultiSaveClassAndItem.Rows[i]["PMA"].ToString().Trim());

                        if (dtMultiSaveClassAndItem.Rows[i]["PATTERN"].ToString().Trim() == "")
                        {
                            htTemp.Add("PATTERN_NO", null);
                        }
                        else
                        {
                            htTemp.Add("PATTERN_NO", dtMultiSaveClassAndItem.Rows[i]["PATTERN"].ToString().Trim());
                        }

                        if (CheckPATTERNSPECExist(htTemp))
                        {
                            dtMultiSaveClassAndItem.Rows[i]["CHAN_NO"] = SLP_StoreChain1.Text;
                            dtMultiSaveClassAndItem.Rows[i]["STORE"] = SLP_Store1.Text;
                            dtMultiSaveClassAndItem.Rows[i]["SPEC_TYPE"] = getSpecTypeChecked();
                            dtMultiSaveClassAndItem.Rows[i]["SPEC_TYPE_NAME"] = getSpecTypeNameChecked();
                            dtMultiSaveClassAndItem.Rows[i]["S_START_DATE"] = SLP_SLPDate2.Text;
                            dtMultiSaveClassAndItem.Rows[i]["S_END_DATE"] = SLP_SLPDate3.Text;
                            dtMultiSaveClassAndItem.Rows[i]["SPEC_QTY"] = SLP_Number1.Text;
                            dtMultiSaveClassAndItem.Rows[i]["REASON"] = SLP_CodeFile1.Text;
                            dtMultiSaveClassAndItem.Rows[i]["EXPLAIN"] = SLP_CodeFile1.DropDownListControl.SelectedItem.Text;
                        }
                        else
                        {
                            dtMultiSaveClassAndItem.Rows.RemoveAt(i);
                        }
                    }



                    if (strErrMsgAfterChecked != "")
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ClientScript", string.Format("alert('{0}');", strErrMsgAfterChecked), true);
                    }


                    GridView1.DataSource = dtMultiSaveClassAndItem;
                    GridView1.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            ErrorMsgLabel.Text = ex.Message;
            UpdatePanel1.Update();
        }
        #endregion
    }
Example #15
0
    private Hashtable GetInputValues()
    {
        #region
        Hashtable htParams = new Hashtable();
        htParams.Clear();
        htParams.Add("ChanNo_Ref", SLP_StoreChain1.Text.Trim());
        htParams.Add("Store_Ref", SLP_Store1.Text.Trim());
        htParams.Add("ChanNo_New", SLP_StoreChain2.Text.Trim());
        htParams.Add("Store_New", SLP_Store2.Text.Trim());
        htParams.Add("UserID", Session["UID"].ToString());

        htParams.Add("Pattern_Ref", SLP_Pattern1.Text.Trim());
        htParams.Add("Pattern_New", SLP_Pattern2.Text.Trim());

        return htParams;
        #endregion
    }
    private void SaveData()
    {
        MasterGroupDAL     _dalGroup     = null;
        MasterGroupRoleDAL _dalGroupRole = null;
        Hashtable          _htParameters = null;
        int iNextID     = 0;
        int iNextIDRole = 0;
        int flag        = 1;

        try
        {
            _dalGroup     = new MasterGroupDAL();
            _htParameters = new Hashtable();

            MPF23.Shared.Mapper.UIToDB.Map(pnlBody.Controls, _htParameters);
            Utility.ApplyDefaultProp(_htParameters);

            if (Request.Params["action"] == "add")
            {
                _dalGroup.Insert(_htParameters, ref iNextID);
            }
            else
            {
                //_htParameters["p_usergroupid"] = Request.Params["id"];
                _dalGroup.Update(_htParameters);
                iNextID = Int32.Parse(lblUSERGROUPID.Text.ToString());
            }
            //_dalJobAccess = new SysJobAccessDAL();
            _htParameters.Clear();
            _dalGroupRole = new MasterGroupRoleDAL();
            _htParameters["p_group_code"] = txtUSERGROUP.Text;
            _dalGroupRole.DeleteByGroupCode(_htParameters);

            _htParameters.Clear();
            #region checkboxChecking
            foreach (GridViewRow gvr in gvwList.Rows)
            {
                MPF23.Shared.Mapper.UIToDB.Map(gvr.Controls, _htParameters);
                _htParameters["p_module_id"]  = gvwList.DataKeys[gvr.RowIndex][0];
                _htParameters["p_group_code"] = txtUSERGROUP.Text;

                Utility.ApplyDefaultProp(_htParameters);
                if (((CheckBox)gvr.FindControl("chkAccess")).Checked)
                {
                    _htParameters["p_action_code"] = "A";
                    _dalGroupRole.Insert(_htParameters, ref iNextIDRole);
                }

                if (((CheckBox)gvr.FindControl("chkNew")).Checked)
                {
                    _htParameters["p_action_code"] = "N";
                    _dalGroupRole.Insert(_htParameters, ref iNextIDRole);
                }

                if (((CheckBox)gvr.FindControl("chkEdit")).Checked)
                {
                    _htParameters["p_action_code"] = "E";
                    _dalGroupRole.Insert(_htParameters, ref iNextIDRole);
                }

                if (((CheckBox)gvr.FindControl("chkDelete")).Checked)
                {
                    _htParameters["p_action_code"] = "D";
                    _dalGroupRole.Insert(_htParameters, ref iNextIDRole);
                }
                if (((CheckBox)gvr.FindControl("chkPrint")).Checked)
                {
                    _htParameters["p_action_code"] = "P";
                    _dalGroupRole.Insert(_htParameters, ref iNextIDRole);
                }
                if (((CheckBox)gvr.FindControl("chkAppr")).Checked)
                {
                    _htParameters["p_action_code"] = "R";
                    _dalGroupRole.Insert(_htParameters, ref iNextIDRole);
                }
            }
            #endregion

            Utility.ShowMessageBox(this, Utility.SAVE_DATA_SUCCESS_MESSAGE, null, "usergroupdetail.aspx?action=edt&id=" + iNextID.ToString());
        }
        catch (Exception ex)
        {
            Utility.ShowMessageBox(this, Utility.SAVE_DATA_FAIL_MESSAGE, ex, null);
        }
    }
Example #17
0
 public static void DeleteAll()
 {
     playerPrefsHashtable.Clear();
 }
Example #18
0
 public void ClearCache()
 {
     cachedData.Clear();
 }
Example #19
0
    private void BindGanttChart(int iPrjRefID)
    {
        IPrjRefID = iPrjRefID;

        if (PAGE_TYPE.Equals("N"))
        {
            _iPrjRefID = WebUtility.GetIntByValueDropDownList(ddlPrjName);
        }

        if (PAGE_TYPE.Equals("N") && _iPrjRefID < 1)
        {
            return;
        }

        Biz_Prj_Schedule objSchedule = new Biz_Prj_Schedule();

        objSchedule.IPrj_Ref_Id = IPrjRefID;
        DataSet ds = objSchedule.GetAllList(objSchedule.IPrj_Ref_Id, 0);

        if (ds.Tables.Count == 0 && ds.Tables[0].Rows.Count == 0)
        {
            return;
        }

        DataSet tmpDs = ds.Clone();

        ds.Relations.Add("NodeRelation"
                         , ds.Tables[0].Columns["TASK_REF_ID"]
                         , ds.Tables[0].Columns["UP_TASK_REF_ID"]
                         , false);

        foreach (DataRow dbRow in ds.Tables[0].Rows)
        {
            if (DataTypeUtility.GetToInt32(dbRow["UP_TASK_REF_ID"]) == 0)
            {
                tmpDs.Tables[0].ImportRow(dbRow);
                PopulateScheduleTree(dbRow, tmpDs);
            }
        }

        _dataTable = tmpDs.Tables[0];

        // Set Gantt chart type
        Chart1.Series["Tasks"].Type    = SeriesChartType.Gantt;
        Chart1.Series["Progress"].Type = SeriesChartType.Gantt;

        Chart1.Legends["Default"].Enabled = true;

        Chart1.ChartAreas["Default"].AxisX.MajorGrid.Interval = 2;
        Chart1.ChartAreas["Default"].AxisX.LabelsAutoFit      = false;

        Chart1.ChartAreas["Default"].AxisX.Interval = 1;
        Chart1.ChartAreas["Default"].AxisX.Reverse  = true;

        Chart1.ChartAreas["Default"].AxisY.LabelStyle.Format = "yy.MM.dd";
        //Chart1.ChartAreas["Default"].AxisY.MajorGrid.Interval = 28;
        //Chart1.ChartAreas["Default"].AxisY.Interval = 10;
        Chart1.ChartAreas["Default"].AxisY.LabelsAutoFitStyle ^= LabelsAutoFitStyle.IncreaseFont;
        Chart1.ChartAreas["Default"].AxisY.LabelsAutoFit       = true;

        Chart1.ChartAreas["Default"].Area3DStyle.Enable3D = false;
        Chart1.Series["Progress"]["DrawSideBySide"]       = "false";
        Chart1.Series["Tasks"]["DrawSideBySide"]          = "false";

        Chart1.Series["Tasks"]["PointWidth"]    = "0.7";
        Chart1.Series["Progress"]["PointWidth"] = "0.4";

        //Chart1.BackColor = Color.White;
        //Chart1.BackGradientType = GradientType.None;
        //Chart1.BorderColor = Color.Gray;
        //Chart1.BorderLineStyle = ChartDashStyle.Solid;
        //Chart1.BorderStyle = ChartDashStyle.NotSet;

        _htPoints.Clear();

        for (int i = 0; i < _dataTable.Rows.Count; i++)
        {
            DataRow row = _dataTable.Rows[i];

            object oPlanStartDate   = row["PLAN_START_DATE"];
            object oPlanEndDate     = row["PLAN_END_DATE"];
            object oActualStartDate = row["ACTUAL_START_DATE"];
            object oActualEndDate   = row["ACTUAL_END_DATE"];

            if (oPlanStartDate.ToString() == oPlanEndDate.ToString() && oPlanEndDate != DBNull.Value)
            {
                oPlanEndDate = (object)DataTypeUtility.GetToDateTime(oPlanEndDate).AddDays(1);
            }

            if (oActualStartDate.ToString() == oActualEndDate.ToString() && oActualEndDate != DBNull.Value)
            {
                oActualEndDate = (object)DataTypeUtility.GetToDateTime(oActualEndDate).AddDays(1);
            }

            if (oPlanStartDate != DBNull.Value && oPlanEndDate != DBNull.Value)
            {
                Chart1.Series["Tasks"].Points.AddXY(i, oPlanStartDate, oPlanEndDate);
            }
            else
            {
                Chart1.Series["Tasks"].Points.AddXY(i, null, null);
            }

            if (oActualStartDate == DBNull.Value || oActualStartDate == null)
            {
                oActualStartDate = null;
            }

            if (oActualEndDate == DBNull.Value || oActualEndDate == null)
            {
                oActualEndDate = null;
            }

            if (oActualStartDate == null || oActualEndDate == null)
            {
                oActualStartDate = null;
                oActualEndDate   = null;
            }

            //if (oActualStartDate == DBNull.Value && oActualEndDate != null)
            //    oActualStartDate =  oPlanStartDate;

            //if (oActualStartDate != DBNull.Value && (oActualEndDate == null || oActualEndDate == DBNull.Value))
            //    oActualEndDate    = oPlanEndDate;

            Chart1.Series["Progress"].Points.AddXY(i, oActualStartDate, oActualEndDate);

            //Chart1.Series["Tasks"].Points.AddXY(i, row["PLAN_START_DATE"], row["PLAN_END_DATE"]);

            //Chart1.Series["Progress"].Points.AddXY(i, row["ACTUAL_START_DATE"], row["ACTUAL_END_DATE"]);

            Chart1.Series["Tasks"].Points[i].AxisLabel    = row["TASK_NAME"].ToString();
            Chart1.Series["Progress"].Points[i].AxisLabel = row["TASK_NAME"].ToString();

            //Chart1.Series["Tasks"].Points[i].ToolTip = "계획기간 : " + DataTypeUtility.GetToDateTimeText(row["PLAN_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["PLAN_END_DATE"]);
            //Chart1.Series["Progress"].Points[i].ToolTip = "계획기간 : " + DataTypeUtility.GetToDateTimeText(row["PLAN_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["PLAN_END_DATE"]);
            //Chart1.Series["Progress"].Points[i].ToolTip = "실행기간 : " + DataTypeUtility.GetToDateTimeText(row["ACTUAL_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["ACTUAL_END_DATE"]);

            if (DataTypeUtility.GetToInt32(row["UP_TASK_REF_ID"]) > 0)
            {
                Chart1.Series["Tasks"].Points[i].ToolTip = "계획기간 : " + DataTypeUtility.GetToDateTimeText(row["PLAN_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["PLAN_END_DATE"]) + "\r\n" +
                                                           "실행기간 : " + DataTypeUtility.GetToDateTimeText(row["ACTUAL_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["ACTUAL_END_DATE"]);

                Chart1.Series["Progress"].Points[i].ToolTip = "계획기간 : " + DataTypeUtility.GetToDateTimeText(row["PLAN_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["PLAN_END_DATE"]) + "\r\n" +
                                                              "실행기간 : " + DataTypeUtility.GetToDateTimeText(row["ACTUAL_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["ACTUAL_END_DATE"]);
            }
            else
            {
                DataSet actualDs = objSchedule.GetActualDate(this.IPrjRefID);

                Chart1.Series["Tasks"].Points[i].ToolTip = "계획기간 : " + DataTypeUtility.GetToDateTimeText(row["PLAN_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["PLAN_END_DATE"]) + "\r\n" +
                                                           "실행기간 : " + DataTypeUtility.GetToDateTimeText(actualDs.Tables[0].Rows[0]["ACTUAL_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(actualDs.Tables[0].Rows[0]["ACTUAL_END_DATE"]);

                Chart1.Series["Progress"].Points[i].ToolTip = "계획기간 : " + DataTypeUtility.GetToDateTimeText(row["PLAN_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(row["PLAN_END_DATE"]) + "\r\n" +
                                                              "실행기간 : " + DataTypeUtility.GetToDateTimeText(actualDs.Tables[0].Rows[0]["ACTUAL_START_DATE"]) + " ~ " + DataTypeUtility.GetToDateTimeText(actualDs.Tables[0].Rows[0]["ACTUAL_END_DATE"]);
            }

            if (DataTypeUtility.GetToInt32(row["UP_TASK_REF_ID"]) > 0)
            {
                Chart1.Series["Tasks"].Points[i].Href    = "javascript:OpenSchedule('" + row["TASK_REF_ID"].ToString() + "');";
                Chart1.Series["Progress"].Points[i].Href = "javascript:OpenSchedule('" + row["TASK_REF_ID"].ToString() + "');";
            }

            //Chart1.Series["Tasks"].Points[i].Label = Chart1.Series["Tasks"].Points[i].XValue.ToString();

            _htPoints.Add(row["TASK_REF_ID"], Chart1.Series["Tasks"].Points[i]);
        }
    }
Example #20
0
 protected void DoIndexing()
 {
     _Items.Clear();
     IndexToolbarItems(this, 0);
 }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Hashtable ht = new Hashtable();
                if (IsValid())
                {
                    ht.Add("Ledger_Code", txtLedgerNumber.Text);
                    ht.Add("Ledger_Name", txtLedgerName.Text);
                    ht.Add("Opening_Balance", Convert.ToDouble(txtLedgerOpeningBal.Text));
                    ht.Add("Opening_Nature", cmbBalanceNature.SelectedItem.Text);
                    ht.Add("Under_ID", Convert.ToInt64(cmbCategoryGroup_Parent.SelectedValue));
                    ht.Add("Group_Name", cmbCategoryGroup_Parent.SelectedItem.Text);

                    ht.Add("Edit_User", Edit_User);
                    ht.Add("Company_Code", CompanyCode);
                    ht.Add("OCode", OCode);

                    int status = objLeg_BLL.Save_Ledger(ht);
                    if (status == 1)
                    {
                        ht.Clear();
                        GetLedgerList();
                        clear();
                        messagePanel.Visible      = true;
                        lblMessage.Text           = "Ledger Created Successfully.";
                        messagePanel.BackColor    = Color.Green;
                        this.lblMessage.ForeColor = Color.White;
                    }
                    else if (status == 5)
                    {
                        ht.Clear();
                        messagePanel.Visible      = true;
                        this.lblMessage.Text      = "Ledger Name and Code both Conflict!!";
                        messagePanel.BackColor    = Color.Red;
                        this.lblMessage.ForeColor = Color.White;
                    }
                    else if (status == 4)
                    {
                        ht.Clear();
                        messagePanel.Visible      = true;
                        this.lblMessage.Text      = "Ledger Name Conflict!!";
                        messagePanel.BackColor    = Color.Red;
                        this.lblMessage.ForeColor = Color.White;
                    }
                    else if (status == 3)
                    {
                        ht.Clear();
                        messagePanel.Visible      = true;
                        this.lblMessage.Text      = "Ledger Code Conflict!!";
                        messagePanel.BackColor    = Color.Red;
                        this.lblMessage.ForeColor = Color.White;
                    }
                    else
                    {
                        ht.Clear();
                        messagePanel.Visible      = true;
                        this.lblMessage.Text      = "Ledger Creation Failed!!";
                        messagePanel.BackColor    = Color.Red;
                        this.lblMessage.ForeColor = Color.White;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblMessage.Text      = ex.Message.ToString();
                messagePanel.BackColor    = Color.Red;
                this.lblMessage.ForeColor = Color.White;
            }
        }
Example #22
0
 public void Dispose()
 {
     UnregisterHotKey(Handle, KeyId);
     KeyPair.Clear();
 }
Example #23
0
    private void TempDataToDataBase()
    {
        #region

        DataTable dtBatchImportResult = null;

        try
        {

            ArrayList arl_Return = null;
            string s_LoginUser = string.Empty;
            string s_UploadPath_File = string.Empty;
            string s_BackPath_File = string.Empty;

            string strSerialBatchNo = "";

            s_LoginUser = Session["UID"].ToString();//登入人員

            Int32 iCurrentImportType = GetCurrentImportType();

            Hashtable HtParams = new Hashtable();
            HtParams.Clear();
            HtParams.Add("IMP_TYPE", iCurrentImportType);
            HtParams.Add("DIS_DATE", SLP_SLPDate1.Text);
            HtParams.Add("ST_ACCEPT_DATE", SLP_SLPDate2.Text);
            HtParams.Add("USER_ID", s_LoginUser);
            HtParams.Add("SESSION_ID", PageTimeStamp.Value);

            if (iCurrentImportType == 1 || iCurrentImportType == 2)
            {
                ALOModel.ImportDisRecord BCO = new ALOModel.ImportDisRecord(ConnectionDB);

                if (s_AP_FileName != string.Empty)
                {
                    arl_Return = BCO.TmpToDB(HtParams, out strSerialBatchNo, out dtBatchImportResult);
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ALO141", "alert('請重新匯入 EXCEL 檔')", true);
                }
            }
            else if (iCurrentImportType == 3)
            {
                ALOModel.ImportDisCRMRecord BCO = new ALOModel.ImportDisCRMRecord(ConnectionDB);

                if (s_AP_FileName != string.Empty)
                {
                    arl_Return = BCO.TmpToDB(HtParams, out strSerialBatchNo, out dtBatchImportResult);
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ALO141", "alert('請重新匯入 EXCEL 檔')", true);
                }

            }

            if (arl_Return[0].ToString() == "TEMPTODB 正確")
            {
                #region 設定 UploadStatusPanel 的值

                //匯入結果
                UploadStatusPanel1.ImportSum = iProcessingCounts;
                UploadStatusPanel1.ImportOK = iProcessingCounts;
                UploadStatusPanel1.ImportNG = 0;

                #endregion

                ShowBatchImportGridView(true, dtBatchImportResult);
            }
            else if (arl_Return[0].ToString() == "CHECKDATA 不正確")
            {
                #region 設定 UploadStatusPanel 的值

                //匯入結果
                UploadStatusPanel1.ImportSum = iProcessingCounts;
                UploadStatusPanel1.ImportOK = 0;
                UploadStatusPanel1.ImportNG = iProcessingCounts;

                #endregion

              ShowBatchImportGridView(false, dtBatchImportResult);
            }
            else //程式錯誤
            {
              #region 設定 UploadStatusPanel 的值
              //上傳結果
              this.UploadStatusPanel1.UploadSum = 0;
              this.UploadStatusPanel1.UploadOK = 0;
              this.UploadStatusPanel1.UploadNG = 0;
              //匯入結果
              this.UploadStatusPanel1.ImportSum = -1;
              this.UploadStatusPanel1.ImportOK = -1;
              this.UploadStatusPanel1.ImportNG = -1;

              #endregion
              throw new Exception(arl_Return[1].ToString());

            }

        }
        catch (Exception ex)
        {
            this.ErrorMsgLabel_PostBack.Text = ex.Message;
            ShowBatchImportGridView(false, dtBatchImportResult);
        }
        finally
        {
            this.but_Temp_To_DB.Enabled = false;
            this.but_File_To_Temp.Enabled = true;
            this.but_Unusual_Report.Enabled = true;
            this.ButtonQuery.Enabled = true;
            this.btn_Exit.Enabled = true;
        }
        #endregion
    }
Example #24
0
        private void BUT_connect_Click(object sender, EventArgs e)
        {
            threadrun = false;
            if (comPort.IsOpen)
            {
                threadrun = false;
                comPort.Close();
                BUT_connect.Text = Strings.Connect;
                try
                {
                    basedata.Close();

                    basedata = null;
                }
                catch
                {
                }
            }
            else
            {
                status_line3 = null;

                try
                {
                    switch (CMB_serialport.Text)
                    {
                        case "NTRIP":
                            comPort = new CommsNTRIP();
                            CMB_baudrate.SelectedIndex = 0;
                            ((CommsNTRIP) comPort).lat = MainV2.comPort.MAV.cs.HomeLocation.Lat;
                            ((CommsNTRIP) comPort).lng = MainV2.comPort.MAV.cs.HomeLocation.Lng;
                            ((CommsNTRIP) comPort).alt = MainV2.comPort.MAV.cs.HomeLocation.Alt;
                            chk_m8pautoconfig.Checked = false;
                            break;
                        case "TCP Client":
                            comPort = new TcpSerial();
                            CMB_baudrate.SelectedIndex = 0;
                            break;
                        case "UDP Host":
                            comPort = new UdpSerial();
                            CMB_baudrate.SelectedIndex = 0;
                            break;
                        case "UDP Client":
                            comPort = new UdpSerialConnect();
                            CMB_baudrate.SelectedIndex = 0;
                            break;
                        default:
                            comPort = new SerialPort();
                            comPort.PortName = CMB_serialport.Text;
                            break;
                    }

                    Settings.Instance["SerialInjectGPS_port"] = CMB_serialport.Text;
                    Settings.Instance["SerialInjectGPS_baud"] = CMB_baudrate.Text;
                }
                catch
                {
                    CustomMessageBox.Show(Strings.InvalidPortName);
                    return;
                }
                try
                {
                    comPort.BaudRate = int.Parse(CMB_baudrate.Text);
                }
                catch
                {
                    CustomMessageBox.Show(Strings.InvalidBaudRate);
                    return;
                }
                try
                {
                    comPort.ReadBufferSize = 1024*64;

                    comPort.Open();

                    try
                    {
                        basedata = new BinaryWriter(new BufferedStream(
                            File.Open(
                                Settings.Instance.LogDir + Path.DirectorySeparatorChar +
                                DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".gpsbase", FileMode.CreateNew,
                                FileAccess.ReadWrite, FileShare.None)));
                    }
                    catch (Exception ex2)
                    {
                        CustomMessageBox.Show("Error creating file to save base data into " + ex2.ToString());
                    }
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show("Error Connecting\nif using com0com please rename the ports to COM??\n" +
                                          ex.ToString());
                    return;
                }

                // inject init strings - m8p
                if (chk_m8pautoconfig.Checked)
                {
                    this.LogInfo("Setup M8P");

                    ubx_m8p.SetupM8P(comPort, basepos, int.Parse(txt_surveyinDur.Text, CultureInfo.InvariantCulture),
                        double.Parse(txt_surveyinAcc.Text, CultureInfo.InvariantCulture), chk_m8p_130p.Checked);

                    this.LogInfo("Setup M8P done");
                }

                t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
                {
                    IsBackground = true,
                    Name = "injectgps"
                };
                t12.Start();

                BUT_connect.Text = Strings.Stop;

                msgseen.Clear();
                bytes = 0;
            }
        }
Example #25
0
        // Render
        public string Render(string aclass, string liclass)
        {
            // Create <A>
            Hashtable attrs = new Hashtable();
            attrs.Add("class", aclass);
            attrs.Add("href", Url);
            attrs.Add("target", Target);
            string innerhtml = ew_HtmlElement("a", attrs, Text, true);
            if (SubMenu != null)
                innerhtml += SubMenu.Render(true);

            // Create <LI>
            attrs.Clear();
            attrs.Add("class", liclass);
            return ew_HtmlElement("li", attrs, innerhtml, true);
        }
Example #26
0
        public void Import(string filepath, System.Windows.Forms.ListView lv, out string msg)
        {
            msg = "";

            FilePathValue = filepath;
            DataTable dt = null;

            try
            {
                dt = this.Excel.GetSchema();

                List <object> Objectlist = null;
                Objectlist = (from dr in dt.AsEnumerable()
                              where dr["TABLE_NAME"].ToString().EndsWith("$")
                              select dr["TABLE_NAME"]).ToList();
                Hashtable hashtb = new Hashtable();
                hashtb.Clear();
                List <string> datas = new List <string>();

                SheetName = "T_RecallUser";//string.Format("{0:MMddHHmmss}", DateTime.Now);//创建导入失败表名称

                foreach (object obj in Objectlist)
                {
                    if (SheetName + "$" == obj.ToString())
                    {
                        SheetName = SheetName + "1";
                    }
                }
                StringBuilder sb = new StringBuilder();

                //DataTable objUserdt = CreateTb();
                //objUserdt.Clear();
                foreach (object obj in Objectlist)
                {
                    DataTable objdt = this.Excel.ReadTable(obj.ToString());
                    for (int i = 1; i < objdt.Rows.Count; i++)
                    {
                        if (Convert.ToInt32(objdt.Rows[i][0]) >= 300000000)
                        {
                            throw new Exception("异常数据发生在用户ID为" + objdt.Rows[i][0] + "上面,请检查数据");
                        }
                        var wid = objdt.Rows[i][0].ToString();
                        if (!lv.Items.ContainsKey(wid))
                        {
                            while (wid.Length < 10)//不足10位前面补0
                            {
                                wid = "0" + wid;
                            }
                            lv.Items.Add(wid, wid, "").SubItems.Add("未处理");
                        }
                    }
                    break;
                }


                //if (objUserdt.Rows.Count > 0)
                //{

                //    //using (DbAction db = new DbAction(str150sync))
                //    //{
                //    //    db.AddDataTable(objUserdt);
                //    //}
                //}
                Excel.Dispose();
                msg = "导入成功!";
            }
            catch (Exception ex)
            {
                Excel.Dispose();
                msg = ex.Message;
            }
        }
Example #27
0
        public void TestGetCountBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            Hashtable ht1 = null;

            string s1 = null;
            string s2 = null;

            int i = 0;

            // Set - null val, should pass

            ht1 = new Hashtable(); //default constructor
            ht1["first key"] = null;
            Assert.Equal(1, ht1.Count);

            //[]  vanila
            ht1 = new Hashtable(); //default constructor
            ht1["first key"] = "first value";
            Assert.Equal(1, ht1.Count);

            //   Set again with a diff value
            ht1["first key"] = "second value";

            // now, size should still be one
            Assert.Equal(1, ht1.Count);

            //[]  Testcase:  add 50 key-val pairs and check the size
            ht1 = new Hashtable();
            for (i = 0; i < 100; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("old_val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                ht1.Add(s1, s2);

                Assert.Equal(i + 1, ht1.Count);
            }

            //
            //[]  Testcase:  now set 100 key-val pairs, this includes the first 50 pairs that
            // just added, their values must be changed to the new values set
            //
            for (i = 0; i < 100; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("new_val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                ht1[s1] = s2;
            }

            Assert.Equal(100, ht1.Count);

            //
            //[] Remove a key and then check size
            //
            sblMsg = new StringBuilder(99);
            sblMsg.Append("key_50");
            s1 = sblMsg.ToString();

            ht1.Remove(s1); //removes "Key_50"
            Assert.Equal(99, ht1.Count);

            //
            //[] clear everything and check the size
            //
            ht1.Clear();
            Assert.Equal(0, ht1.Count);
        }
Example #28
0
        private void PopulateWindowMenu()
        {
            if (mdilist)
            {
                if (mdilist_items == null)
                {
                    mdilist_items = new Hashtable();
                    mdilist_forms = new Hashtable();
                }

                do
                {
                    MainMenu main = GetMainMenu();
                    if (main == null || main.GetForm() == null)
                    {
                        break;
                    }

                    Form form = main.GetForm();
                    mdicontainer = form.MdiContainer;
                    if (mdicontainer == null)
                    {
                        break;
                    }


                    // Remove closed forms
                    MenuItem[] items = new MenuItem[mdilist_items.Count];
                    mdilist_items.Keys.CopyTo(items, 0);
                    foreach (MenuItem item in items)
                    {
                        Form mdichild = (Form)mdilist_items [item];
                        if (!mdicontainer.mdi_child_list.Contains(mdichild))
                        {
                            mdilist_items.Remove(item);
                            mdilist_forms.Remove(mdichild);
                            MenuItems.Remove(item);
                        }
                    }

                    // Add new forms and update state for existing forms.
                    for (int i = 0; i < mdicontainer.mdi_child_list.Count; i++)
                    {
                        Form     mdichild = (Form)mdicontainer.mdi_child_list[i];
                        MenuItem item;
                        if (mdilist_forms.Contains(mdichild))
                        {
                            item = (MenuItem)mdilist_forms [mdichild];
                        }
                        else
                        {
                            item = new MenuItem();
                            item.is_window_menu_item = true;
                            item.Click              += new EventHandler(MdiWindowClickHandler);
                            mdilist_items [item]     = mdichild;
                            mdilist_forms [mdichild] = item;
                            MenuItems.AddNoEvents(item);
                        }
                        item.Visible = mdichild.Visible;
                        item.Text    = "&" + (i + 1).ToString() + " " + mdichild.Text;
                        item.Checked = form.ActiveMdiChild == mdichild;
                    }
                }while (false);
            }
            else
            {
                // Remove all forms
                if (mdilist_items != null)
                {
                    foreach (MenuItem item in mdilist_items.Values)
                    {
                        MenuItems.Remove(item);
                    }

                    mdilist_forms.Clear();
                    mdilist_items.Clear();
                }
            }
        }
Example #29
0
    protected void btn_CopyDetail_Click(object sender, EventArgs e)
    {
        #region

        ALOModel.MaintainPatternSpec BCO = new ALOModel.MaintainPatternSpec(ConnectionDB);

        Hashtable htParams = new Hashtable();
        htParams.Clear();
        htParams.Add("ChanNo", SLP_StoreChain1.Text.Trim());
        htParams.Add("STORE", SLP_Store1.Text.Trim());

        DataTable dtDetl = BCO.QueryLastPATTERNSPECDetail(htParams);



        if (dtDetl != null && dtDetl.Rows.Count > 0)
        {
            dtDetailData = dtDetl;
            gv_Detail.DataSource = dtDetl;
            gv_Detail.DataBind();
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ClientScript", "alert('此門市無前筆有效明細設定資訊,請手動新增');", true);
        }




        #endregion
    }
Example #30
0
        } // DoParse

        private void ParseRtf(TextReader reader)
        {
            _curText = new StringBuilder();

            _unicodeSkipCountStack.Clear();
            _codePageStack.Clear();
            _unicodeSkipCount         = 1;
            _level                    = 0;
            _tagCountAtLastGroupStart = 0;
            _tagCount                 = 0;
            _fontTableStartLevel      = -1;
            _targetFont               = null;
            _expectingThemeFont       = false;
            _fontToCodePageMapping.Clear();
            _hexDecodingBuffer.SetLength(0);
            UpdateEncoding(RtfSpec.AnsiCodePage);
            var       groupCount = 0;
            const int eof        = -1;
            var       nextChar   = PeekNextChar(reader, false);
            var       backslashAlreadyConsumed = false;

            while (nextChar != eof)
            {
                var peekChar      = 0;
                var peekCharValid = false;
                switch (nextChar)
                {
                case '\\':
                    if (!backslashAlreadyConsumed)
                    {
                        reader.Read();     // must still consume the 'peek'ed char
                    }
                    var secondChar = PeekNextChar(reader, true);
                    switch (secondChar)
                    {
                    case '\\':
                    case '{':
                    case '}':
                        _curText.Append(ReadOneChar(reader));         // must still consume the 'peek'ed char
                        break;

                    case '\n':
                    case '\r':
                        reader.Read();         // must still consume the 'peek'ed char
                        // must be treated as a 'par' tag if preceded by a backslash
                        // (see RTF spec page 144)
                        HandleTag(reader, new RtfTag(RtfSpec.TagParagraph));
                        break;

                    case '\'':
                        reader.Read();         // must still consume the 'peek'ed char
                        var hex1 = (char)ReadOneByte(reader);
                        var hex2 = (char)ReadOneByte(reader);
                        if (!IsHexDigit(hex1))
                        {
                            throw new RtfHexEncodingException(Strings.InvalidFirstHexDigit(hex1));
                        }
                        if (!IsHexDigit(hex2))
                        {
                            throw new RtfHexEncodingException(Strings.InvalidSecondHexDigit(hex2));
                        }
                        var decodedByte = int.Parse("" + hex1 + hex2, NumberStyles.HexNumber);
                        _hexDecodingBuffer.WriteByte((byte)decodedByte);
                        peekChar      = PeekNextChar(reader, false);
                        peekCharValid = true;
                        var mustFlushHexContent = true;
                        if (peekChar == '\\')
                        {
                            reader.Read();
                            backslashAlreadyConsumed = true;
                            var continuationChar = PeekNextChar(reader, false);
                            if (continuationChar == '\'')
                            {
                                mustFlushHexContent = false;
                            }
                        }
                        if (mustFlushHexContent)
                        {
                            DecodeCurrentHexBuffer();
                        }
                        break;

                    case '|':
                    case '~':
                    case '-':
                    case '_':
                    case ':':
                    case '*':
                        HandleTag(reader, new RtfTag("" + ReadOneChar(reader)));
                        // must still consume the 'peek'ed char
                        break;

                    default:
                        ParseTag(reader);
                        break;
                    }
                    break;

                case '\n':
                case '\r':
                    reader.Read();     // must still consume the 'peek'ed char
                    break;

                case '\t':
                    reader.Read();     // must still consume the 'peek'ed char
                    // should be treated as a 'tab' tag (see RTF spec page 144)
                    HandleTag(reader, new RtfTag(RtfSpec.TagTabulator));
                    break;

                case '{':
                    reader.Read();     // must still consume the 'peek'ed char
                    FlushText();
                    NotifyGroupBegin();
                    _tagCountAtLastGroupStart = _tagCount;
                    _unicodeSkipCountStack.Push(_unicodeSkipCount);
                    _codePageStack.Push(_encoding == null ? 0 : _encoding.CodePage);
                    _level++;
                    break;

                case '}':
                    reader.Read();     // must still consume the 'peek'ed char
                    FlushText();
                    if (_level > 0)
                    {
                        _unicodeSkipCount = (int)_unicodeSkipCountStack.Pop();
                        if (_fontTableStartLevel == _level)
                        {
                            _fontTableStartLevel = -1;
                            _targetFont          = null;
                            _expectingThemeFont  = false;
                        }
                        UpdateEncoding((int)_codePageStack.Pop());
                        _level--;
                        NotifyGroupEnd();
                        groupCount++;
                    }
                    else
                    {
                        throw new RtfBraceNestingException(Strings.ToManyBraces);
                    }
                    break;

                default:
                    _curText.Append(ReadOneChar(reader));     // must still consume the 'peek'ed char
                    break;
                }
                if (_level == 0 && IgnoreContentAfterRootGroup)
                {
                    break;
                }
                if (peekCharValid)
                {
                    nextChar = peekChar;
                }
                else
                {
                    nextChar = PeekNextChar(reader, false);
                    backslashAlreadyConsumed = false;
                }
            }
            FlushText();
            reader.Close();

            if (_level > 0)
            {
                throw new RtfBraceNestingException(Strings.ToFewBraces);
            }
            if (groupCount == 0)
            {
                throw new RtfEmptyDocumentException(Strings.NoRtfContent);
            }
            _curText = null;
        } // ParseRtf
Example #31
0
        internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies)
        {
            FileIOPermission.Assert();
            Compiler compiler = new Compiler();

            try {
                Hashtable scopeTable = new Hashtable();
                foreach (XmlMapping mapping in xmlMappings)
                {
                    scopeTable[mapping.Scope] = mapping;
                }
                TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count];
                scopeTable.Keys.CopyTo(scopes, 0);

                assemblies.Clear();
                Hashtable importedTypes = new Hashtable();
                foreach (TypeScope scope in scopes)
                {
                    foreach (Type t in scope.Types)
                    {
                        compiler.AddImport(t, importedTypes);
                        Assembly a    = t.Assembly;
                        string   name = a.FullName;
                        if (assemblies[name] != null)
                        {
                            continue;
                        }
                        if (!a.GlobalAssemblyCache)
                        {
                            assemblies[name] = a;
                        }
                    }
                }
                for (int i = 0; i < types.Length; i++)
                {
                    compiler.AddImport(types[i], importedTypes);
                }
                compiler.AddImport(typeof(object).Assembly);
                compiler.AddImport(typeof(XmlSerializer).Assembly);

                IndentedWriter writer = new IndentedWriter(compiler.Source, false);

                writer.WriteLine("#if _DYNAMIC_XMLSERIALIZER_COMPILATION");
                writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]");
                writer.WriteLine("[assembly:System.Security.SecurityTransparent()]");
                writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]");
                writer.WriteLine("#endif");
                // Add AssemblyVersion attribute to match parent accembly version
                if (types != null && types.Length > 0 && types[0] != null)
                {
                    writer.WriteLine("[assembly:System.Reflection.AssemblyVersionAttribute(\"" + types[0].Assembly.GetName().Version.ToString() + "\")]");
                }
                if (assembly != null && types.Length > 0)
                {
                    for (int i = 0; i < types.Length; i++)
                    {
                        Type type = types[i];
                        if (type == null)
                        {
                            continue;
                        }
                        if (DynamicAssemblies.IsTypeDynamic(type))
                        {
                            throw new InvalidOperationException(Res.GetString(Res.XmlPregenTypeDynamic, types[i].FullName));
                        }
                    }
                    writer.Write("[assembly:");
                    writer.Write(typeof(XmlSerializerVersionAttribute).FullName);
                    writer.Write("(");
                    writer.Write("ParentAssemblyId=");
                    ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]));
                    writer.Write(", Version=");
                    ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version);
                    if (defaultNamespace != null)
                    {
                        writer.Write(", Namespace=");
                        ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace);
                    }
                    writer.WriteLine(")]");
                }
                CodeIdentifiers classes = new CodeIdentifiers();
                classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter");
                classes.AddUnique("XmlSerializationReader", "XmlSerializationReader");
                string suffix = null;
                if (types != null && types.Length == 1 && types[0] != null)
                {
                    suffix = CodeIdentifier.MakeValid(types[0].Name);
                    if (types[0].IsArray)
                    {
                        suffix += "Array";
                    }
                }

                writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {");
                writer.Indent++;

                writer.WriteLine();

                string writerClass = "XmlSerializationWriter" + suffix;
                writerClass = classes.AddUnique(writerClass, writerClass);
                XmlSerializationWriterCodeGen writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass);

                writerCodeGen.GenerateBegin();
                string[] writeMethodNames = new string[xmlMappings.Length];

                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]);
                }
                writerCodeGen.GenerateEnd();

                writer.WriteLine();

                string readerClass = "XmlSerializationReader" + suffix;
                readerClass = classes.AddUnique(readerClass, readerClass);
                XmlSerializationReaderCodeGen readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass);

                readerCodeGen.GenerateBegin();
                string[] readMethodNames = new string[xmlMappings.Length];
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]);
                }
                readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types);

                string    baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes);
                Hashtable serializers    = new Hashtable();
                for (int i = 0; i < xmlMappings.Length; i++)
                {
                    if (serializers[xmlMappings[i].Key] == null)
                    {
                        serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass);
                    }
                }
                readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers);
                writer.Indent--;
                writer.WriteLine("}");

                return(compiler.Compile(assembly, defaultNamespace, parameters, evidence));
            }
            finally {
                compiler.Close();
            }
        }
Example #32
0
 /// <summary>
 /// Empties the cache of all items.
 /// </summary>
 public static void FlushCache()
 {
     _cache.Clear();
 }
Example #33
0
        public void TestAddWithReferenceTypeValues()
        {
            StringBuilder sbl3 = new StringBuilder(99);
            StringBuilder sbl4 = new StringBuilder(99);
            StringBuilder sbl5 = new StringBuilder(99);
            StringBuilder sblWork1 = new StringBuilder(99);

            // Examine whether this Collection stores a ref to the provided object or a copy of the object (should store ref).
            var ht2 = new Hashtable();

            sbl3.Length = 0;
            sbl3.Append("key_f3");

            sbl4.Length = 0;
            sbl4.Append("value_f3");

            ht2.Add(sbl3, sbl4);

            sbl4.Length = 0;
            sbl4.Append("value_f4");  // Modify object referenced by ht2, changing its value.

            sblWork1 = (StringBuilder)ht2[sbl3];
            Assert.True(sblWork1.ToString().Equals(sbl4.ToString()));

            // Examine "backdoor duplicate" behavior - should be ok as both
            // GetHashCode && Equals are checked before insert/get in the current impl.
            ht2 = new Hashtable();

            sbl3.Length = 0;
            sbl3.Append("key_m5");

            sbl4.Length = 0;
            sbl4.Append("value_m5");

            ht2.Add(sbl3, sbl4);

            sbl5 = new StringBuilder("key_p7"); //new memory SBL Obj

            sbl4.Length = 0;
            sbl4.Append("value_p7");

            ht2.Add(sbl5, sbl4);
            sbl5.Length = 0; //"No Object" key

            Assert.Equal(2, ht2.Count);
            sbl5.Append("key_m5"); // Backdoor duplicate!

            sblWork1 = (StringBuilder)ht2[sbl5];
            Assert.True(ht2.ContainsKey(sbl5));

            ht2.Clear();
          }
Example #34
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //****************************************************//
            if (Session["collegecode"] == null)
            {
                Response.Redirect("~/Default.aspx");
            }

            if (!Request.FilePath.Contains("CoeHome"))
            {
                string strPreviousPage = "";
                if (Request.UrlReferrer != null)
                {
                    strPreviousPage = Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1];
                }
                if (strPreviousPage == "")
                {
                    Response.Redirect("~/CoeMod/CoeHome.aspx");
                    return;
                }
            }
            //****************************************************//
            usercode    = Session["usercode"].ToString();
            collegecode = Session["collegecode"].ToString();
            singleuser  = Session["single_user"].ToString();
            group_user  = Session["group_code"].ToString();
            if (group_user.Contains(';'))
            {
                string[] group_semi = group_user.Split(';');
                group_user = group_semi[0].ToString();
            }
            errmsg.Visible = false;
            if (!IsPostBack)
            {
                string group_code  = Session["group_code"].ToString();
                string columnfield = "";
                if (group_code.Contains(';'))
                {
                    string[] group_semi = group_code.Split(';');
                    group_code = group_semi[0].ToString();
                }
                if ((group_code.ToString().Trim() != "") && (Session["single_user"].ToString() != "1" && Session["single_user"].ToString() != "true" && Session["single_user"].ToString() != "TRUE" && Session["single_user"].ToString() != "True"))
                {
                    columnfield = " and group_code='" + group_code + "'";
                }
                else
                {
                    columnfield = " and user_code='" + Session["usercode"] + "'";
                }
                hat.Clear();
                hat.Add("column_field", columnfield.ToString());
                ds = d2.select_method("bind_college", hat, "sp");
                ddlcollege.Items.Clear();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ddlcollege.Enabled        = true;
                    ddlcollege.DataSource     = ds;
                    ddlcollege.DataTextField  = "collname";
                    ddlcollege.DataValueField = "college_code";
                    ddlcollege.DataBind();
                    loadedu();
                    loadbatch();
                    loadsubtype();
                    year();
                    month();
                }
                clear();
            }
        }
        catch (Exception ex)
        { }
    }
    private void LoadList()
    {
        string sSelect = "SELECT Clinic.Name AS ClinicName, [" + TableName + "].ClientID";
        string sInnerjoin = "\n INNER JOIN Clinic ON [" + TableName + "].ClientID = Clinic.Id";
        string sWhere = "\n WHERE Clinic.Id =" + ddlClinic.SelectedValue + " ";
        string sSQL = string.Empty;
        string sListFields = string.Empty;
        List<SqlParameter> parames = new List<SqlParameter>();
        Hashtable hashParames = new Hashtable();
        int i = -1;

        if (searchConditions != null && !string.IsNullOrEmpty(TableName) && TableName.Length > 0)
        {
            var conditionTables = new Hashtable();
            conditionTables.Add("Clinic", "Clinic");
            foreach (SearchExpander seardcondition in searchConditions)
            {
                i++;
                object requesCondition = Request[GetIDControl(seardcondition.ColumnName, seardcondition.Refference, seardcondition.DisplayRefferenceColumn)];
                SqlParameter param = null;
                if (seardcondition.Type == null) sSelect += ", [" + TableName + "]." + seardcondition.ColumnName;
                if (seardcondition.Refference != null)
                {
                    string BeetwenRefTableName = WebCore.GetTableName(seardcondition.Type);
                    string RefTableName = WebCore.GetTableName(seardcondition.Refference);
                    //Add column to sellect
                    sSelect += ", [" + RefTableName + "]." + seardcondition.DisplayRefferenceColumn + " as " + RefTableName + seardcondition.DisplayRefferenceColumn;

                    //===========================================================================
                    //Join table has column refference
                    if (!conditionTables.ContainsKey(RefTableName))
                    {
                        if (seardcondition.Type == null)
                        {
                            sInnerjoin += "\n LEFT OUTER JOIN [" + RefTableName + "] ON [" + RefTableName + "]." + seardcondition.RefferenceColumn + " = [" + TableName + "]." + seardcondition.ColumnName;
                            conditionTables.Add(RefTableName, RefTableName);
                        }
                        else
                        {
                            sInnerjoin += "\n LEFT OUTER JOIN [" + RefTableName + "] ON [" + RefTableName + "]." + seardcondition.RefferenceColumn + " = [" + BeetwenRefTableName + "]." + seardcondition.ColumnName;
                            conditionTables.Add(RefTableName, RefTableName);
                        }
                    }

                    //===========================================================================
                    // Where if search something in search textbox
                    if (requesCondition != null && requesCondition.ToString() != string.Empty)
                    {
                        //Where condition
                        sWhere += " AND  [" + RefTableName + "]." + seardcondition.DisplayRefferenceColumn + " LIKE '%' + @" + RefTableName + seardcondition.DisplayRefferenceColumn + " + '%' ";
                        //Param
                        param = new SqlParameter("@" + RefTableName + seardcondition.DisplayRefferenceColumn, requesCondition ?? string.Empty);
                        if (!hashParames.ContainsKey(param.ParameterName)) { parames.Add(param); hashParames.Add(param.ParameterName, param.ParameterName); }
                    }
                }
                //Check condition
                else if (requesCondition != null && requesCondition.ToString() != string.Empty)
                {
                    // Select like when search in string type
                    if (seardcondition.PKType == typeof(string))
                    {
                        sWhere += " AND " + TableName + ".[" + seardcondition.ColumnName + "] LIKE '%' + @" + seardcondition.ColumnName + " + '%' ";
                        sSQL += " AND " + TableName + ".[" + seardcondition.ColumnName + "] LIKE '%' + @" + seardcondition.ColumnName + " + '%' ";
                        param = new SqlParameter("@" + seardcondition.ColumnName, requesCondition ?? string.Empty);
                    }
                    //Select validate value
                    else
                    {
                        sWhere += " AND " + TableName + ".[" + seardcondition.ColumnName + "] = @" + seardcondition.ColumnName + " ";
                        sSQL += " AND " + TableName + ".[" + seardcondition.ColumnName + "] = @" + seardcondition.ColumnName + " ";
                        param = new SqlParameter("@" + seardcondition.ColumnName, requesCondition ?? DBNull.Value);
                    }
                    if (!hashParames.ContainsKey(param.ParameterName)) { parames.Add(param); hashParames.Add(param.ParameterName, param.ParameterName); }
                }
            }
            // Check with client ID
            if (!string.IsNullOrEmpty(ClientID)) sWhere += " AND [" + TableName + "].ClientId=" + ClientID;
            if (!string.IsNullOrEmpty(Id)) sWhere += " AND [" + TableName + "].Id=" + Id;
            hashParames.Clear();
            hashParames = null;

            //Check group by
            if (this.GroupBy != null)
            {
                sWhere += " AND [" + TableName + "]." + this.GroupBy.ColumnName;
                if (this.GroupBy.PKType == typeof(DateTime))
                {
                    sWhere += " between @" + this.GroupBy.ColumnName + " AND @" + this.GroupBy.ColumnName + "2";
                    DateTime selectDate = DateTime.Today;
                    DateTime.TryParseExact(txtGroupBy.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out selectDate);
                    SqlParameter param1 = new SqlParameter("@" + this.GroupBy.ColumnName, selectDate);
                    SqlParameter param2 = new SqlParameter("@" + this.GroupBy.ColumnName + "2", selectDate.AddDays(1));
                    parames.Add(param1);
                    parames.Add(param2);
                }
            }

            // Group all querry
            sSelect += " FROM [" + TableName + "]";
            sSQL = sSelect + sInnerjoin + sWhere;
            DataSet dataset = SqlHelper.ExecuteDataset(Config.SVConnectionString, CommandType.Text, sSQL, parames.ToArray());
            gvListData.AutoGenerateColumns = false;
            gvListData.DataSource = dataset;
            gvListData.DataBind();
            parames.Clear();
            parames = null;

            if (dataset != null && dataset.Tables.Count > 0) pager.ItemCount = dataset.Tables[0].Rows.Count;
        }
    }
 /// <devdoc>
 ///    <para>
 ///       Clears the collection of members.
 ///    </para>
 /// </devdoc>
 public void Clear()
 {
     data.Clear();
     keys.Clear();
 }
Example #37
0
        public void TestGetKeys()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            Hashtable ht1 = null;

            string s1 = null;
            string s2 = null;
            string s3 = null;

            object[] objArr;

            ICollection icol1;
            IEnumerator ienm1;

            int i = 0;
            int iCount = 0;

            ht1 = new Hashtable();
            for (i = 0; i < 100; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                ht1.Add(s1, s2);
            }

            //
            // test Get to make sure the key-vals are accessible
            //
            for (i = 0; i < ht1.Count; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                s3 = (string)ht1[s1];

                Assert.Equal(s3, s2);
            }

            //
            // []  now GetKeys and make sure every key is obtained
            //  NOTE: the keys obtained may not necessarily be in any order
            //
            int temp = ht1.Count;
            objArr = new object[temp];

            ht1.Keys.CopyTo(objArr, 0);
            Assert.Equal(objArr.Length, ht1.Count);

            for (i = 0; i < objArr.Length; i++)
            {
                Assert.True(ht1.ContainsKey(objArr[i].ToString()));
            }

            // [] We test other methods in the Collection to make sure that they work!!
            icol1 = ht1.Keys;
            ienm1 = icol1.GetEnumerator();
            iCount = 0;
            while (ienm1.MoveNext())
            {
                iCount++;
                Assert.True(ht1.ContainsKey(ienm1.Current));
            }

            Assert.Equal(iCount, ht1.Count);
            Assert.Equal(icol1.Count, ht1.Count);
            Assert.False(icol1.IsSynchronized);
            Assert.Equal(icol1.SyncRoot, ht1.SyncRoot);

            Assert.Throws<ArgumentException>( () => 
            {
                object[,] mdObjArray = new object[ht1.Keys.Count, ht1.Keys.Count];
                ht1.Keys.CopyTo(mdObjArray, 0);
            });

            //[] The ICollection is alive - i.e. whatever changes we do to the Underlying HT is reflected in the collection
            sblMsg = new StringBuilder();
            sblMsg.Append("key_");
            sblMsg.Append(0);
            s1 = sblMsg.ToString();

            ht1.Remove(s1);
            ienm1 = icol1.GetEnumerator();
            iCount = 0;
            while (ienm1.MoveNext())
            {
                s3 = (string)ienm1.Current;
                Assert.NotEqual(s1, s3);
            }

            Assert.Equal(icol1.Count, ht1.Count);
            //[] we will clear the HT and make sure that the Keys are kaput
            ht1.Clear();
            Assert.Equal(0, icol1.Count);

            iCount = 0;
            ienm1 = icol1.GetEnumerator();
            while (ienm1.MoveNext())
            {
                iCount++;
            }

            Assert.Equal(0, iCount);
        }
Example #38
0
 public void Clear()
 {
     ClearEscherRecords();
     shapeToObj.Clear();
     //        lastShapeId = 1024;
 }
    private void GenerateRoutine(string classID, string employeeID, string subjectID)
    {
        Hashtable htRoutineValues = new Hashtable();

        string crValue = string.Empty;

        DataRow newRow = null;
        DataSet dsRoutine = new DataSet();
        DataSet dsWeekDay = new DataSet();

        dsRoutine.Clear();
        STD_RoutineByValueManager STD_RoutineByValueManager = new STD_RoutineByValueManager();
        dsRoutine = STD_RoutineByValueManager.GetSTD_RoutineByParam(subjectID, employeeID, classID);
        dsWeekDay = STD_RoutineByValueManager.GetSTD_WeekDay();
        //string[] weekDayNames1= dsWeekDay.Tables[0].AsEnumerable().Select(dr => dr["Name"].ToString()).ToArray();

        DataSet ds = GetTemplate();

        if (dsRoutine.Tables[0].Columns.Contains("subjectname"))
            dsRoutine.Tables[0].Columns.Remove("subjectname");

        if (dsRoutine.Tables[0].Columns.Contains("Order"))
            dsRoutine.Tables[0].Columns.Remove("Order");

        string[] columnNames = (from dc in dsRoutine.Tables[0].Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
        string[] allColumnNames = (from dc in ds.Tables["tblRoutineTemplate"].Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();

        //string[] weekDayNames = { "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "", "Days" };
        //string[] weekDayNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames;
        string[] weekDayNames = dsWeekDay.Tables[0].AsEnumerable().Select(dr => dr["Name"].ToString()).ToArray();

        if(dsRoutine.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < dsRoutine.Tables[0].Rows.Count; i++)
            {
                for (int j = 0; j < columnNames.Count(); j++)
                {
                    string rowValue = String.Empty, columnName = String.Empty, currDay = String.Empty;
                    rowValue = dsRoutine.Tables[0].Rows[i][j].ToString();
                    currDay = dsRoutine.Tables[0].Rows[i][0].ToString();
                    columnName = columnNames[j].ToString();

                    if (prevDayName == currDay)
                    {
                        string parameter = "Days = '" + prevDayName + "'";

                        if (!weekDayNames.Contains(columnName))
                        {
                            if (htRoutineValues[columnName] == null)
                            {
                                htRoutineValues.Add(columnName, rowValue);
                                crValue = htRoutineValues[columnName].ToString();
                                rowValue = crValue;
                            }
                            else
                            {
                                if ((rowValue != htRoutineValues[columnName].ToString()) && rowValue != "")
                                {
                                    if (htRoutineValues[columnName].ToString() == "" || rowValue == "")
                                        crValue = rowValue;
                                    else
                                        crValue = rowValue + ", " + htRoutineValues[columnName].ToString();

                                    htRoutineValues[columnName] = crValue;
                                    rowValue = crValue;
                                }
                            }
                        }

                        DataRow[] rows = ds.Tables["tblRoutineTemplate"].Select(parameter);
                        string rowname = columnName;
                        if (allColumnNames.Contains(columnName))
                        {
                            if (rowValue != String.Empty)
                            {
                                rows[0][rowname] = rowValue;
                                rows[0].AcceptChanges();
                                rows[0].SetModified();
                            }
                        }
                    }
                    else
                    {
                        htRoutineValues.Clear();
                        if (!weekDayNames.Contains(columnName))
                        {
                            htRoutineValues.Add(columnName, rowValue);
                        }
                        newRow = ds.Tables["tblRoutineTemplate"].NewRow();
                        string rowname = columnName;
                        if (allColumnNames.Contains(columnName))
                        {
                            newRow[rowname] = rowValue;
                            ds.Tables["tblRoutineTemplate"].Rows.Add(newRow);
                        }
                    }
                    prevDayName = dsRoutine.Tables[0].Rows[i][0].ToString();
                    rowValue = String.Empty;
                    prevColName = columnName;
                }
            }
            Session["tblRoutineTemplate"] = ds;
            Comm_Display_Routine dRoutine = new Comm_Display_Routine();
            dvAddRoutine.InnerHtml = dRoutine.ConvertDataTableToHTMLString(ds.Tables["tblRoutineTemplate"], "2px", "1", true, true);
        }
        else
        {
            ds.Clear();
            Session["tblRoutineTemplate"] = null;
            dvAddRoutine.InnerHtml = "No Record Found";
        }
    }
        public void Activate()
        {
            if (!MainV2.comPort.BaseStream.IsOpen)
            {
                Enabled = false;
                return;
            }
            if (MainV2.comPort.MAV.cs.firmware == Firmwares.ArduCopter2)
            {
                Enabled = true;
            }
            else
            {
                Enabled = false;
                return;
            }

            startup = true;

            changes.Clear();

            // ensure the fields are populated before setting them
            TUNE.setup(
                ParameterMetaDataRepository.GetParameterOptionsInt("TUNE", MainV2.comPort.MAV.cs.firmware.ToString())
                .ToList(), "TUNE", MainV2.comPort.MAV.param);

            CH7_OPTION.setup(new[] { "CH7_OPTION", "RC7_OPTION" }, MainV2.comPort.MAV.param);
            CH8_OPTION.setup(new[] { "CH8_OPTION", "RC8_OPTION" }, MainV2.comPort.MAV.param);
            CH9_OPTION.setup(new[] { "CH9_OPTION", "RC9_OPTION" }, MainV2.comPort.MAV.param);
            CH10_OPTION.setup(new[] { "CH10_OPTION", "RC10_OPTION" }, MainV2.comPort.MAV.param);

            TUNE_LOW.setup(0, 10000, 1000, 0.01f, "TUNE_LOW", MainV2.comPort.MAV.param);
            TUNE_HIGH.setup(0, 10000, 1000, 0.01f, "TUNE_HIGH", MainV2.comPort.MAV.param);

            HLD_LAT_P.setup(0, 0, 1, 0.001f, new[] { "HLD_LAT_P", "POS_XY_P", "PSC_POSXY_P" }, MainV2.comPort.MAV.param);
            LOITER_LAT_D.setup(0, 0, 1, 0.001f, new[] { "LOITER_LAT_D", "PSC_VELXY_D" }, MainV2.comPort.MAV.param);
            LOITER_LAT_I.setup(0, 0, 1, 0.001f, new[] { "LOITER_LAT_I", "VEL_XY_I", "PSC_VELXY_I" }, MainV2.comPort.MAV.param);
            LOITER_LAT_IMAX.setup(0, 0, 10, 1f, new[] { "LOITER_LAT_IMAX", "VEL_XY_IMAX", "PSC_VELXY_IMAX" }, MainV2.comPort.MAV.param);
            LOITER_LAT_P.setup(0, 0, 1, 0.001f, new[] { "LOITER_LAT_P", "VEL_XY_P", "PSC_VELXY_P" }, MainV2.comPort.MAV.param);

            RATE_PIT_D.setup(0, 0, 1, 0.001f, new[] { "RATE_PIT_D", "ATC_RAT_PIT_D" }, MainV2.comPort.MAV.param);
            RATE_PIT_I.setup(0, 0, 1, 0.001f, new[] { "RATE_PIT_I", "ATC_RAT_PIT_I" }, MainV2.comPort.MAV.param);
            if (MainV2.comPort.MAV.param.ContainsKey("ATC_RAT_PIT_IMAX")) // 3.4 changes scaling
            {
                RATE_PIT_IMAX.setup(0, 0, 1, 1f, new[] { "ATC_RAT_PIT_IMAX" }, MainV2.comPort.MAV.param);
            }
            else
            {
                RATE_PIT_IMAX.setup(0, 0, 10, 1f, new[] { "RATE_PIT_IMAX" }, MainV2.comPort.MAV.param);
            }
            RATE_PIT_P.setup(0, 0, 1, 0.001f, new[] { "RATE_PIT_P", "ATC_RAT_PIT_P" }, MainV2.comPort.MAV.param);
            RATE_PIT_FILT.setup(0, 0, 1, 0.001f, new[] { "RATE_PIT_FILT", "ATC_RAT_PIT_FILT" }, MainV2.comPort.MAV.param);

            RATE_RLL_D.setup(0, 0, 1, 0.001f, new[] { "RATE_RLL_D", "ATC_RAT_RLL_D" }, MainV2.comPort.MAV.param);
            RATE_RLL_I.setup(0, 0, 1, 0.001f, new[] { "RATE_RLL_I", "ATC_RAT_RLL_I" }, MainV2.comPort.MAV.param);
            if (MainV2.comPort.MAV.param.ContainsKey("ATC_RAT_RLL_IMAX")) // 3.4 changes scaling
            {
                RATE_RLL_IMAX.setup(0, 0, 1, 1f, new[] { "ATC_RAT_RLL_IMAX" }, MainV2.comPort.MAV.param);
            }
            else
            {
                RATE_RLL_IMAX.setup(0, 0, 10, 1f, new[] { "RATE_RLL_IMAX" }, MainV2.comPort.MAV.param);
            }
            RATE_RLL_P.setup(0, 0, 1, 0.001f, new[] { "RATE_RLL_P", "ATC_RAT_RLL_P" }, MainV2.comPort.MAV.param);
            RATE_RLL_FILT.setup(0, 0, 1, 0.001f, new[] { "RATE_RLL_FILT", "ATC_RAT_RLL_FILT" }, MainV2.comPort.MAV.param);

            RATE_YAW_D.setup(0, 0, 1, 0.001f, new[] { "RATE_YAW_D", "ATC_RAT_YAW_D" }, MainV2.comPort.MAV.param);
            RATE_YAW_I.setup(0, 0, 1, 0.001f, new[] { "RATE_YAW_I", "ATC_RAT_YAW_I" }, MainV2.comPort.MAV.param);
            if (MainV2.comPort.MAV.param.ContainsKey("ATC_RAT_YAW_IMAX")) // 3.4 changes scaling
            {
                RATE_YAW_IMAX.setup(0, 0, 1, 1f, new[] { "ATC_RAT_YAW_IMAX" }, MainV2.comPort.MAV.param);
            }
            else
            {
                RATE_YAW_IMAX.setup(0, 0, 10, 1f, new[] { "RATE_YAW_IMAX" }, MainV2.comPort.MAV.param);
            }
            RATE_YAW_P.setup(0, 0, 1, 0.001f, new[] { "RATE_YAW_P", "ATC_RAT_YAW_P" }, MainV2.comPort.MAV.param);
            RATE_YAW_FILT.setup(0, 0, 1, 0.001f, new[] { "RATE_YAW_FILT", "ATC_RAT_YAW_FILT" }, MainV2.comPort.MAV.param);

            STB_PIT_P.setup(0, 0, 1, 0.001f, new[] { "STB_PIT_P", "ATC_ANG_PIT_P" }, MainV2.comPort.MAV.param);
            STB_RLL_P.setup(0, 0, 1, 0.001f, new[] { "STB_RLL_P", "ATC_ANG_RLL_P" }, MainV2.comPort.MAV.param);
            STB_YAW_P.setup(0, 0, 1, 0.001f, new[] { "STB_YAW_P", "ATC_ANG_YAW_P" }, MainV2.comPort.MAV.param);

            THR_ACCEL_D.setup(0, 0, 1, 0.001f, new[] { "THR_ACCEL_D", "ACCEL_Z_D", "PSC_ACCZ_D" }, MainV2.comPort.MAV.param);
            THR_ACCEL_I.setup(0, 0, 1, 0.001f, new[] { "THR_ACCEL_I", "ACCEL_Z_I", "PSC_ACCZ_I" }, MainV2.comPort.MAV.param);
            THR_ACCEL_IMAX.setup(0, 0, 10, 1f, new[] { "THR_ACCEL_IMAX", "ACCEL_Z_IMAX", "PSC_ACCZ_IMAX" }, MainV2.comPort.MAV.param);
            THR_ACCEL_P.setup(0, 0, 1, 0.001f, new[] { "THR_ACCEL_P", "ACCEL_Z_P", "PSC_ACCZ_P" }, MainV2.comPort.MAV.param);
            THR_ALT_P.setup(0, 0, 1, 0.001f, new[] { "THR_ALT_P", "POS_Z_P", "PSC_POSZ_P" }, MainV2.comPort.MAV.param);
            THR_RATE_P.setup(0, 0, 1, 0.001f, new[] { "THR_RATE_P", "VEL_Z_P", "PSC_VELZ_P" }, MainV2.comPort.MAV.param);

            WPNAV_LOIT_SPEED.setup(0, 0, 1, 0.001f, new[] { "WPNAV_LOIT_SPEED", "LOIT_SPEED" }, MainV2.comPort.MAV.param);
            WPNAV_RADIUS.setup(0, 0, 1, 0.001f, "WPNAV_RADIUS", MainV2.comPort.MAV.param);
            WPNAV_SPEED.setup(0, 0, 1, 0.001f, "WPNAV_SPEED", MainV2.comPort.MAV.param);
            WPNAV_SPEED_DN.setup(0, 0, 1, 0.001f, "WPNAV_SPEED_DN", MainV2.comPort.MAV.param);
            WPNAV_SPEED_UP.setup(0, 0, 1, 0.001f, "WPNAV_SPEED_UP", MainV2.comPort.MAV.param);

            // unlock entries if they differ
            if (RATE_RLL_P.Value != RATE_PIT_P.Value || RATE_RLL_I.Value != RATE_PIT_I.Value ||
                RATE_RLL_D.Value != RATE_PIT_D.Value || RATE_RLL_IMAX.Value != RATE_PIT_IMAX.Value)
            {
                CHK_lockrollpitch.Checked = false;
            }

            if (MainV2.comPort.MAV.param["H_SWASH_TYPE"] != null)
            {
                CHK_lockrollpitch.Checked = false;
            }

            // add tooltips to all controls
            foreach (Control control1 in Controls)
            {
                foreach (Control control2 in control1.Controls)
                {
                    if (control2 is MavlinkNumericUpDown)
                    {
                        var ParamName = ((MavlinkNumericUpDown)control2).ParamName;
                        toolTip1.SetToolTip(control2,
                                            ParameterMetaDataRepository.GetParameterMetaData(ParamName,
                                                                                             ParameterMetaDataConstants.Description, MainV2.comPort.MAV.cs.firmware.ToString()));
                    }
                    if (control2 is MavlinkComboBox)
                    {
                        var ParamName = ((MavlinkComboBox)control2).ParamName;
                        toolTip1.SetToolTip(control2,
                                            ParameterMetaDataRepository.GetParameterMetaData(ParamName,
                                                                                             ParameterMetaDataConstants.Description, MainV2.comPort.MAV.cs.firmware.ToString()));
                    }
                }
            }

            startup = false;
        }
Example #41
0
    protected int PullPrjBoard(bool PullActiveOnly, bool UpdateProjects)
    {
        string output = "";     //holds label output
        int count = 0;          //count of number of projects pulled, will return this value

        Lists listService = new Lists();
        ProjectsBLL project = new ProjectsBLL();

        listService.PreAuthenticate = true;
        listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

        XmlDocument xmlDoc = new XmlDocument();
        XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
        XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
        XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

        ndQueryOptions.InnerXml = "";// "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" + "<DateInUtc>TRUE</DateInUtc>";
        ndViewFields.InnerXml = "";// "<FieldRef Name='Title'/><FieldRef Name='Column5'/><FieldRef Name='Column4'/><FieldRef Name='Completed'/><FieldRef Name='Column12'/><FieldRef Name='Project_x0020_Site_x0020_URL'/><FieldRef Name='Project_x0020_Manager2'/><FieldRef Name='IT_x0020_Technical_x0020_Lead'/><FieldRef Name='Project_x0020_Phase'/>";

        //query XML with only completed items or all items?
        if (PullActiveOnly)
            ndQuery.InnerXml = "<Where><Eq><FieldRef Name='Completed'/><Value Type='Number'>0</Value></Eq></Where>";
        else
            ndQuery.InnerXml = "";

        try
        {
            XmlNode ndListItems;
            Hashtable prjHash = new Hashtable();

            //call web service to get all the projects from the PMO Project Board
            ndListItems = listService.GetListItems(PROJECT_BOARD_GUID, PROJECT_BOARD_VIEW_GUID, ndQuery, ndViewFields, null, ndQueryOptions);

            //create xml document so we can process
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(ndListItems.OuterXml);

            foreach (XmlNode element in doc.ChildNodes[0].ChildNodes[0].ChildNodes)
            {
                if (element.Attributes != null)
                {
                    foreach (XmlAttribute attr in element.Attributes)
                    {
                        switch (attr.Name)
                        {
                            //TODO: This will be different based on the fields in your SharePoint list.
                            case "ows_Title":
                                prjHash.Add("ProjectNumber", attr.Value);
                                break;
                            case "ows_NSR_x002f_Project_x0020_Name":
                                prjHash.Add("Name", attr.Value);
                                break;
                            case "ows_Completed":
                                //list contains 0 if not compeleted and -1 if completed
                                if (Convert.ToInt32(attr.Value) == 0)
                                    prjHash.Add("Active", true);
                                else
                                    prjHash.Add("Active", false);
                                break;
                            case "ows_Approved":
                                prjHash.Add("Approved", attr.Value);
                                break;
                            case "ows_Current_x0020_Status":
                                prjHash.Add("Status", attr.Value);
                                break;
                            case "ows_Project_x0020_Site_x0020_URL":
                                //list returns value as url,url.  we only need it once, so using split we take the first one
                                prjHash.Add("SiteURL", attr.Value.Split(',')[0]);
                                break;
                            case "ows_Project_x0020_Manager":
                                prjHash.Add("ProjectManager", attr.Value.Split('#')[1]);
                                break;
                            case "ows_Project_x0020_Phase":
                                prjHash.Add("PhaseID", attr.Value);
                                break;
                            case "ows_ID":
                                //once the attribute equals "ows_ID" we know we can process

                                //setup some temp holders
                                int projectID = Convert.ToInt32(attr.Value);
                                string number = prjHash["ProjectNumber"].ToString();
                                string name = prjHash["Name"].ToString();

                                string projectManager;
                                if (prjHash.ContainsKey("ProjectManager"))
                                    projectManager = prjHash["ProjectManager"].ToString();
                                else
                                    projectManager = "";

                                string siteURL;
                                if (prjHash.ContainsKey("SiteURL"))
                                    siteURL = prjHash["SiteURL"].ToString();
                                else
                                    siteURL = null;

                                int phaseID;
                                if (prjHash.ContainsKey("PhaseID"))
                                {
                                    switch (prjHash["PhaseID"].ToString())
                                    {
                                        case "Initiating":
                                            phaseID = 0;
                                            break;
                                        case "Planning":
                                            phaseID = 1;
                                            break;
                                        case "Execution":
                                            phaseID = 2;
                                            break;
                                        case "Monitoring":
                                            phaseID = 3;
                                            break;
                                        case "Closing":
                                            phaseID = 4;
                                            break;
                                        case "Proposals":
                                            phaseID = 5;
                                            break;
                                        case "Startups/Turndowns":
                                            phaseID = 6;
                                            break;
                                        case "Startup":
                                            phaseID = 7;
                                            break;
                                        case "Turndown":
                                            phaseID = 8;
                                            break;
                                        case "Win-awaiting NTP":
                                            phaseID = 9;
                                            break;
                                        default:
                                            phaseID = -1;
                                            break;
                                    }
                                }
                                else
                                    phaseID = -1;

                                bool active;
                                if (Convert.ToBoolean(prjHash["Active"]) && (prjHash["Approved"].ToString() == "Approved as Project" || prjHash["Approved"].ToString() == "NSR Analysis"))
                                    active = true;
                                else
                                    active = false;

                                //DEBUG PRINT
                                //output += "<tr><td>Debug: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";

                                //first we check to see if this project already exists
                                if (project.ProjectIDExists(projectID) < 1)
                                {
                                    output += "<tr><td>Adding: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";

                                    //add the project to the db, first checking to see if SiteURL exists and is not empty
                                    if (prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty)
                                        project.AddProject(projectID, number, name, siteURL, active, phaseID, projectManager);
                                    else
                                        project.AddProject(projectID, number, name, null, active, phaseID, projectManager);

                                    output += "<td>Complete!</td></tr>";

                                    count++;
                                }
                                else
                                {
                                    //otherwise the project already exists and we can update it
                                    if (UpdateProjects)
                                    {
                                        TimeKeeper.ProjectsDataTable prj = project.GetProjectByProjectID(projectID);
                                        TimeKeeper.ProjectsRow prjRow = prj[0];

                                        //output += "<tr><td>Update - " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                        //output += "<tr><td>active = " + active.ToString() + "</tr></td>";
                                        //count++;

                                        if (prjRow.Active != active)
                                        {
                                            //RUN DEACTIVATE PROJECT CODE HERE
                                            if (active == false)
                                            {
                                                ProjectMembersBLL projectMembers = new ProjectMembersBLL();

                                                int membersDeleted = projectMembers.DeleteProjectMembersByProjectID(projectID);

                                                output += "<tr><td>Deactivating: " + number + " - " + name + ", Removed " + membersDeleted.ToString() + " member(s)</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                                project.UpdateProject(projectID, number, name, null, false, phaseID, projectManager);
                                                output += "<td>Complete!</td></tr>";
                                            }
                                            else
                                            {
                                                output += "<tr><td>Activating: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                                project.UpdateProject(projectID, number, name, null, true, phaseID, projectManager);
                                                output += "<td>Complete!</td></tr>";
                                            }
                                            count++;
                                        }

                                        if (prjRow.ProjectNumber != number || prjRow.Name != name || prjRow.PhaseID != phaseID || prjRow.ProjectManager.ToString() != projectManager)
                                        {
                                            //it does exist, print message
                                            output += "<tr><td>Updating: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";

                                            if (prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty)
                                            {
                                                project.UpdateProject(projectID, number, name, siteURL, active, phaseID, projectManager);
                                            }
                                            else
                                            {
                                                project.UpdateProject(projectID, number, name, null, active, phaseID, projectManager);
                                            }
                                            output += "<td>Complete!</td></tr>";

                                            count++;
                                        }
                                        if (prjRow.IsTeamSiteURLNull() && prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty)
                                        {
                                            //there is a new team site that we need to add
                                            output += "<tr><td>Team Site added: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                            project.UpdateProject(projectID, number, name, siteURL, active, phaseID, projectManager);
                                            output += "<td>Complete!</td></tr>";

                                            count++;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }

                //clear the hash for the next element
                prjHash.Clear();
            }
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
            output = ex.StackTrace;
        }

        //set label
        PullOutputLabel.Text = output;

        return count;
    }
Example #42
0
        /// <summary>
        ///     Encode the raw data using the EAN-13 algorithm. (Can include the checksum already.  If it doesnt exist in the data
        ///     then it will calculate it for you.  Accepted data lengths are 12 + 1 checksum or just the 12 data digits)
        /// </summary>
        private string Encode_EAN13()
        {
            //check length of input
            if (Raw_Data.Length < 12 || Raw_Data.Length > 13)
            {
                throw new Exception("EEAN13-1: Data length invalid. (Length must be 12 or 13)");
            }

            if (!Barcode.CheckNumericOnly(Raw_Data))
            {
                throw new Exception("EEAN13-2: Numeric Data Only");
            }

            var patterncode = EAN_Pattern[int.Parse(Raw_Data[0].ToString())];
            var result      = "101";

            var pos = 0;

            while (pos < 6)
            {
                if (patterncode[pos] == 'a')
                {
                    result += EAN_CodeA[int.Parse(Raw_Data[pos + 1].ToString())];
                }
                if (patterncode[pos] == 'b')
                {
                    result += EAN_CodeB[int.Parse(Raw_Data[pos + 1].ToString())];
                }
                pos++;
            }

            //add divider bars
            result += "01010";

            //get the third
            pos = 1;
            while (pos <= 5)
            {
                result += EAN_CodeC[int.Parse(Raw_Data[pos++ + 6].ToString())];
            }

            //checksum digit
            var cs = int.Parse(Raw_Data[Raw_Data.Length - 1].ToString());

            //add checksum
            result += EAN_CodeC[cs];

            //add ending bars
            result += "101";

            //get the manufacturer assigning country
            init_CountryCodes();
            _Country_Assigning_Manufacturer_Code = "N/A";
            var twodigitCode   = Raw_Data.Substring(0, 2);
            var threedigitCode = Raw_Data.Substring(0, 3);

            try
            {
                _Country_Assigning_Manufacturer_Code = CountryCodes[threedigitCode].ToString();
            }
            catch
            {
                try
                {
                    _Country_Assigning_Manufacturer_Code = CountryCodes[twodigitCode].ToString();
                }
                catch
                {
                    throw new Exception("EEAN13-3: Country assigning manufacturer code not found.");
                }
            }
            finally
            {
                CountryCodes.Clear();
            }

            return(result);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentMaster.Title.TitleText = GetString("customtable.data.selectdisplayedfields");
        CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_CustomTables/selectfields.png");
        CurrentMaster.DisplayActionsPanel = true;

        // Get custom table id from url
        customTableId = QueryHelper.GetInteger("customtableid", 0);

        dci = DataClassInfoProvider.GetDataClass(customTableId);
        // Set edited object
        EditedObject = dci;

        // If class exists
        if (dci != null)
        {
            // Check 'Read' permission
            if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.customtables", "Read") &&
                !CMSContext.CurrentUser.IsAuthorizedPerClassName(dci.ClassName, "Read"))
            {
                lblError.Visible = true;
                lblError.Text = String.Format(GetString("customtable.permissiondenied.read"), dci.ClassName);
                plcContent.Visible = false;
                return;
            }

            btnSelectAll.Text = GetString("UniSelector.SelectAll");
            btnUnSelectAll.Text = GetString("UniSelector.DeselectAll");

            Hashtable reportFields = new Hashtable();

            FormInfo fi = null;

            if (!RequestHelper.IsPostBack())
            {
                btnOk.Text = GetString("General.OK");
                btnCancel.Text = GetString("General.Cancel");

                // Get report fields
                if (!String.IsNullOrEmpty(dci.ClassShowColumns))
                {
                    reportFields.Clear();

                    foreach (string field in dci.ClassShowColumns.Split(';'))
                    {
                        // Add field key to hastable
                        reportFields[field] = null;
                    }
                }

                // Get columns names
                fi = FormHelper.GetFormInfo(dci.ClassName, false);
                string[] columnNames = fi.GetColumnNames();

                if (columnNames != null)
                {
                    foreach (string name in columnNames)
                    {
                        FormFieldInfo ffi = fi.GetFormField(name);

                        // Add checkboxes to the list
                        ListItem item = new ListItem(ResHelper.LocalizeString(GetFieldCaption(ffi, name)), name);
                        if (reportFields.Contains(name))
                        {
                            // Select checkbox if field is reported
                            item.Selected = true;
                        }
                        chkListFields.Items.Add(item);
                    }
                }
            }
        }
    }
Example #44
0
        public ServerMessage method_12(GameClient Session, int int_0)
        {
            Func <RoomData, bool> func  = null;
            Func <Room, bool>     func2 = null;

            Navigator.Class219 @class = new Navigator.Class219();
            @class.int_0 = int_0;
            ServerMessage Message = new ServerMessage(451u);

            if (@class.int_0 >= -1)
            {
                Message.AppendInt32(@class.int_0);
                Message.AppendInt32(1);
            }
            else
            {
                if (@class.int_0 == -2)
                {
                    Message.AppendInt32(0);
                    Message.AppendInt32(2);
                }
                else
                {
                    if (@class.int_0 == -3)
                    {
                        Message.AppendInt32(0);
                        Message.AppendInt32(5);
                    }
                    else
                    {
                        if (@class.int_0 == -4)
                        {
                            Message.AppendInt32(0);
                            Message.AppendInt32(3);
                        }
                        else
                        {
                            if (@class.int_0 == -5)
                            {
                                Message.AppendInt32(0);
                                Message.AppendInt32(4);
                            }
                        }
                    }
                }
            }
            Message.AppendStringWithBreak("");
            List <RoomData> list = new List <RoomData>();

            switch (@class.int_0)
            {
            case -5:
            case -4:
                break;

            case -3:
                goto IL_3A2;

            case -2:
                goto IL_3E5;

            case -1:
                goto IL_47E;

            default:
            {
                Dictionary <Room, int> dictionary = GoldTree.GetGame().GetRoomManager().method_21();
                IEnumerable <RoomData> arg_11F_0  = GoldTree.GetGame().GetRoomManager().list_3;
                if (func == null)
                {
                    func = new Func <RoomData, bool>(@class.method_0);
                }
                IEnumerable <RoomData> enumerable = arg_11F_0.Where(func);
                IEnumerable <Room>     arg_13E_0  = dictionary.Keys;
                if (func2 == null)
                {
                    func2 = new Func <Room, bool>(@class.method_1);
                }
                IEnumerable <Room> arg_160_0 = arg_13E_0.Where(func2);
                if (Navigator.func_2 == null)
                {
                    Navigator.func_2 = new Func <Room, int>(Navigator.smethod_3);
                }
                IOrderedEnumerable <Room> orderedEnumerable = arg_160_0.OrderByDescending(Navigator.func_2);
                new List <RoomData>();
                int num = 0;
                foreach (Room current in orderedEnumerable)
                {
                    if (num > 40)
                    {
                        break;
                    }
                    list.Add(current.Class27_0);
                    num++;
                }
                using (IEnumerator <RoomData> enumerator2 = enumerable.GetEnumerator())
                {
                    while (enumerator2.MoveNext())
                    {
                        RoomData current2 = enumerator2.Current;
                        if (num > 40)
                        {
                            break;
                        }
                        if (list.Contains(current2))
                        {
                            list.Remove(current2);
                        }
                        list.Add(current2);
                        num++;
                    }
                    goto IL_508;
                }
            }
            }
            List <string>          list2       = new List <string>();
            Dictionary <int, Room> dictionary2 = new Dictionary <int, Room>();
            Hashtable hashtable = Session.GetHabbo().GetMessenger().method_26().Clone() as Hashtable;
            Dictionary <RoomData, int> dictionary3 = new Dictionary <RoomData, int>();

            foreach (MessengerBuddy class2 in hashtable.Values)
            {
                if (class2.Boolean_0 && class2.Boolean_1)
                {
                    GameClient class3 = GoldTree.GetGame().GetClientManager().method_2(class2.UInt32_0);
                    if (class3 != null && class3.GetHabbo() != null && class3.GetHabbo().CurrentRoom != null)
                    {
                        RoomData class27_ = class3.GetHabbo().CurrentRoom.Class27_0;
                        if (!dictionary3.ContainsKey(class27_))
                        {
                            dictionary3.Add(class27_, class27_.UsersNow);
                        }
                    }
                }
            }
            IEnumerable <RoomData> arg_344_0 = dictionary3.Keys;

            if (Navigator.func_0 == null)
            {
                Navigator.func_0 = new Func <RoomData, int>(Navigator.smethod_1);
            }
            IOrderedEnumerable <RoomData> orderedEnumerable2 = arg_344_0.OrderByDescending(Navigator.func_0);

            list2.Clear();
            dictionary2.Clear();
            hashtable.Clear();
            dictionary3.Clear();
            using (IEnumerator <RoomData> enumerator2 = orderedEnumerable2.GetEnumerator())
            {
                while (enumerator2.MoveNext())
                {
                    RoomData current3 = enumerator2.Current;
                    list.Add(current3);
                }
                goto IL_508;
            }
IL_3A2:
            using (List <RoomData> .Enumerator enumerator4 = Session.GetHabbo().list_6.GetEnumerator())
            {
                while (enumerator4.MoveNext())
                {
                    RoomData current3 = enumerator4.Current;
                    list.Add(current3);
                }
                goto IL_508;
            }
IL_3E5:
            DataTable dataTable;

            using (DatabaseClient class4 = GoldTree.GetDatabase().GetClient())
            {
                dataTable = class4.ReadDataTable("SELECT * FROM rooms WHERE score > 0 AND roomtype = 'private' ORDER BY score DESC LIMIT 40");
            }
            IEnumerator enumerator3 = dataTable.Rows.GetEnumerator();

            try
            {
                while (enumerator3.MoveNext())
                {
                    DataRow dataRow = (DataRow)enumerator3.Current;
                    list.Add(GoldTree.GetGame().GetRoomManager().method_17((uint)dataRow["Id"], dataRow));
                }
                goto IL_508;
            }
            finally
            {
                IDisposable disposable = enumerator3 as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
IL_47E:
            Dictionary <Room, int> dictionary4 = GoldTree.GetGame().GetRoomManager().method_21();
            IEnumerable <Room> arg_4B3_0       = dictionary4.Keys;

            if (Navigator.func_1 == null)
            {
                Navigator.func_1 = new Func <Room, int>(Navigator.smethod_2);
            }
            IOrderedEnumerable <Room> orderedEnumerable3 = arg_4B3_0.OrderByDescending(Navigator.func_1);
            int num2 = 0;

            foreach (Room current4 in orderedEnumerable3)
            {
                if (num2 >= 40)
                {
                    break;
                }
                num2++;
                list.Add(current4.Class27_0);
            }
IL_508:
            Message.AppendInt32(list.Count);
            foreach (RoomData current5 in list)
            {
                current5.method_3(Message, false, false);
            }
            Random random = new Random();

            Message.AppendStringWithBreak("");
            this.dictionary_1.ElementAt(random.Next(0, this.dictionary_1.Count)).Value.method_0(Message);
            return(Message);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (EditedObject == null)
        {
            RedirectToAccessDenied(GetString("general.invalidparameters"));
        }

        Save += btnOK_Click;

        var user = MembershipContext.AuthenticatedUser;

        // Check permissions for Forms application
        if (!user.IsAuthorizedPerUIElement("cms.form", "Form"))
        {
            RedirectToUIElementAccessDenied("cms.form", "Form");
        }

        // Check 'ReadData' permission
        if (!user.IsAuthorizedPerResource("cms.form", "ReadData", SiteInfoProvider.GetSiteName(FormInfo.FormSiteID)))
        {
            RedirectToAccessDenied("cms.form", "ReadData");
        }

        // Check authorized roles for this form
        if (!FormInfo.IsFormAllowedForUser(MembershipContext.AuthenticatedUser.UserName, SiteContext.CurrentSiteName))
        {
            RedirectToAccessDenied(GetString("Bizforms.FormNotAllowedForUserRoles"));
        }

        List<String> columnNames = null;
        DataClassInfo dci = null;
        Hashtable reportFields = new Hashtable();
        FormInfo fi = null;

        // Initialize controls
        PageTitle.TitleText = GetString("BizForm_Edit_Data_SelectFields.Title");
        CurrentMaster.DisplayActionsPanel = true;

        HeaderActions.AddAction(new HeaderAction
        {
            Text = GetString("UniSelector.SelectAll"),
            OnClientClick = "ChangeFields(true); return false;",
            ButtonStyle = ButtonStyle.Default,
        });

        HeaderActions.AddAction(new HeaderAction
        {
            Text = GetString("UniSelector.DeselectAll"),
            OnClientClick = "ChangeFields(false); return false;",
            ButtonStyle = ButtonStyle.Default,
        });

        if (!RequestHelper.IsPostBack())
        {

            if (FormInfo != null)
            {
                // Get dataclass info
                dci = DataClassInfoProvider.GetDataClassInfo(FormInfo.FormClassID);

                if (dci != null)
                {
                    // Get columns names
                    fi = FormHelper.GetFormInfo(dci.ClassName, false);

                    columnNames = fi.GetColumnNames(false);
                }

                // Get report fields
                if (String.IsNullOrEmpty(FormInfo.FormReportFields))
                {
                    reportFields = LoadReportFields(columnNames);
                }
                else
                {
                    reportFields.Clear();

                    foreach (string field in FormInfo.FormReportFields.Split(';'))
                    {
                        // Add field key to hastable
                        reportFields[field] = null;
                    }
                }

                if (columnNames != null)
                {
                    FormFieldInfo ffi = null;
                    ListItem item = null;

                    MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + FormInfo.ClassName);

                    foreach (string name in columnNames)
                    {
                        ffi = fi.GetFormField(name);

                        // Add checkboxes to the list
                        item = new ListItem(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(GetFieldCaption(ffi, name, resolver))), name);
                        if (reportFields.Contains(name))
                        {
                            // Select checkbox if field is reported
                            item.Selected = true;
                        }
                        chkListFields.Items.Add(item);
                    }
                }
            }
        }
    }
Example #46
0
        private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc)
        {
            if (hash2 == null)
            {
                Assert.Equal(0, hash1.Count);
            }
            else
            {
                // Make sure that construtor imports all keys and values
                Assert.Equal(hash2.Count, hash1.Count);
                for (int i = 0; i < 100; i++)
                {
                    Assert.True(hash1.ContainsKey(i));
                    Assert.True(hash1.ContainsValue(i));
                }

                // Make sure the new and old hashtables are not linked
                hash2.Clear();
                for (int i = 0; i < 100; i++)
                {
                    Assert.True(hash1.ContainsKey(i));
                    Assert.True(hash1.ContainsValue(i));
                }
            }

            Assert.Equal(ikc, hash1.EqualityComparer);

            Assert.False(hash1.IsFixedSize);
            Assert.False(hash1.IsReadOnly);
            Assert.False(hash1.IsSynchronized);

            // Make sure we can add to the hashtable
            int count = hash1.Count;
            for (int i = count; i < count + 100; i++)
            {
                hash1.Add(i, i);
                Assert.True(hash1.ContainsKey(i));
                Assert.True(hash1.ContainsValue(i));
            }
        }
 private void btn_Tax_Upload_Click(object sender, EventArgs e)
 {
     if (string.IsNullOrEmpty(txt_Tax_Dscription.Text.Trim()))
     {
         MessageBox.Show("Enter Description of Uploading File");
         txt_Tax_Dscription.Focus();
         return;
     }
     if (ddl_document_Type.SelectedIndex < 1)
     {
         MessageBox.Show("Select Document Type");
         ddl_document_Type.Focus();
         return;
     }
     try
     {
         SplashScreenManager.ShowForm(this, typeof(Masters.WaitForm1), true, true, false);
         Hashtable      htorderkb = new Hashtable();
         DataTable      dtorderkb = new DataTable();
         OpenFileDialog op1       = new OpenFileDialog();
         op1.Multiselect = true;
         op1.ShowDialog();
         op1.Filter = "allfiles|*.xls";
         int count = 0;
         foreach (string file in op1.FileNames)
         {
             FileInfo f = new FileInfo(file);
             File_size   = GetFileSize(f.Length);
             ftpfullpath = "ftp://" + Ftp_Domain_Name + "/Ftp_Application_Files/OMS/Inhouse_Tax_Documents/" + directoryPath + "";
             string ftpUploadFullPath = "" + ftpfullpath + "/" + f.Name + "";
             // Checking File Exit or not
             FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpfullpath);               // FTP Address
             ftpRequest.Credentials = new NetworkCredential(@"" + Ftp_User_Name + "", Ftp_Password); // Credentials
             ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
             FtpWebResponse   response     = (FtpWebResponse)ftpRequest.GetResponse();
             StreamReader     streamReader = new StreamReader(response.GetResponseStream());
             HashSet <string> files        = new HashSet <string>(); // create list to store directories.
             string           line         = streamReader.ReadLine();
             while (!string.IsNullOrEmpty(line))
             {
                 files.Add(line); // Add Each file to the List.
                 line = streamReader.ReadLine();
             }
             if (!files.Contains(f.Name))
             {
                 FtpWebRequest ftpUpLoadFile = (FtpWebRequest)WebRequest.Create(ftpUploadFullPath);
                 ftpUpLoadFile.Credentials = new NetworkCredential(@"" + Ftp_User_Name + "", Ftp_Password);
                 ftpUpLoadFile.KeepAlive   = true;
                 ftpUpLoadFile.UseBinary   = true;
                 ftpUpLoadFile.Method      = WebRequestMethods.Ftp.UploadFile;
                 FileStream fs        = File.OpenRead(file);
                 Stream     ftpstream = ftpUpLoadFile.GetRequestStream();
                 fs.CopyTo(ftpstream);
                 fs.Close();
                 ftpstream.Close();
                 count++;
                 htorderkb.Clear();
                 dtorderkb.Clear();
                 htorderkb.Add("@Trans", "INSERT");
                 htorderkb.Add("@Order_Id", Order_Id);
                 htorderkb.Add("@Instuction", txt_Tax_Dscription.Text.ToString());
                 htorderkb.Add("@Document_Path", ftpUploadFullPath);
                 htorderkb.Add("@Document_Type", ddl_document_Type.SelectedValue.ToString());
                 htorderkb.Add("@Tax_Task", Task_Id);
                 htorderkb.Add("@FileSize", File_size);
                 htorderkb.Add("@File_Extension", f.Extension);
                 htorderkb.Add("@Inserted_By", User_ID);
                 htorderkb.Add("@status", "True");
                 htorderkb.Add("@Check_Status", "False");
                 dtorderkb = dataaccess.ExecuteSP("Sp_Tax_Orders_Documents", htorderkb);
             }
             else
             {
                 throw new WebException("File Already Exists");
             }
         }
         if (User_Role == "1")
         {
             Gridview_bind_Tax_Admin_Side_Document_Upload();
         }
         else
         {
             Gridview_bind_Tax_Employee_Side_Document_Upload();
         }
         txt_Tax_Dscription.Text = "";
         //ddl_document_Type.SelectedIndex = 0;
         SplashScreenManager.CloseForm(false);
         MessageBox.Show(count + " File(s) copied");
     }
     catch (WebException ex)
     {
         SplashScreenManager.CloseForm(false);
         XtraMessageBox.Show(ex.Message);
     }
     catch (Exception ex)
     {
         SplashScreenManager.CloseForm(false);
         XtraMessageBox.Show("something went wrong");
     }
     finally
     {
         SplashScreenManager.CloseForm(false);
     }
 }
Example #48
0
 public void ReleaseResAll()
 {
     ResHashScene.Clear();
     ResHashScenes.Clear();
     Resources.UnloadUnusedAssets();
 }
 internal void Clear()
 {
     m_lookupTable?.Clear();
 }
 public void Clear()
 {
     _col.Clear();
 }
Example #51
0
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        #region
        Int32 iResult = 0;

        try
        {
            if (dtMultiSaveClassAndItem.Rows.Count > 0)
            {
                Hashtable htTemp = new Hashtable();
                Hashtable htParams = new Hashtable();

                htTemp.Clear();
                htTemp.Add("ChanNo", SLP_StoreChain1.Text.Trim());
                htTemp.Add("Store", SLP_Store1.Text.Trim());
                htTemp.Add("StartDate", SLP_SLPDate2.Text.Trim());
                htTemp.Add("EndDate", SLP_SLPDate3.Text.Trim());

                if (CheckSpecTypeAndValue() && CheckDetailDataIsNotNull() && CheckPATTERNSPECCanAdd(htTemp) )
                {
                    #region
                    DataTable dtForUpdate = dtDetailData;//.GetChanges(DataRowState.Added);

                    ALOModel.MaintainPatternSpec BCO = new ALOModel.MaintainPatternSpec(ConnectionDB);
                    string strCode = "";

                    strErrMsgAfterChecked = "";//清空暫存錯誤訊息

                    for (Int32 i = 0; i <= dtMultiSaveClassAndItem.Rows.Count - 1; i++)
                    {
                        #region Master

                        htTemp.Clear();
                        htTemp.Add("ChanNo", SLP_StoreChain1.Text.Trim());
                        htTemp.Add("Store", SLP_Store1.Text.Trim());
                        htTemp.Add("ROOT_NO", dtMultiSaveClassAndItem.Rows[i]["ROOT_NO"].ToString().Trim());
                        htTemp.Add("PMA", dtMultiSaveClassAndItem.Rows[i]["PMA"].ToString().Trim());

                        if (dtMultiSaveClassAndItem.Rows[i]["PATTERN"].ToString().Trim() == "")
                        {
                            htTemp.Add("PATTERN_NO", null);
                        }
                        else
                        {
                            htTemp.Add("PATTERN_NO", dtMultiSaveClassAndItem.Rows[i]["PATTERN"].ToString().Trim());
                        }

                        if (CheckPATTERNSPECExist(htTemp))
                        {
                            strCode = string.Format("{0}_{1}_{2}_{3}_{4}",
                            SLP_StoreChain1.Text.Trim(), SLP_Store1.Text.Trim(),
                            dtMultiSaveClassAndItem.Rows[i]["ROOT_NO"].ToString().Trim(),
                            dtMultiSaveClassAndItem.Rows[i]["PMA"].ToString().Trim(),
                            dtMultiSaveClassAndItem.Rows[i]["PATTERN"].ToString().Trim());

                            htParams.Clear();
                            htParams.Add("CODE", strCode);
                            htParams.Add("UserID", Session["UID"].ToString());
                            htParams.Add("ChanNO", SLP_StoreChain1.Text.Trim());
                            htParams.Add("STORE", SLP_Store1.Text.Trim());
                            htParams.Add("ROOT_NO", dtMultiSaveClassAndItem.Rows[i]["ROOT_NO"].ToString().Trim());
                            htParams.Add("PMA", dtMultiSaveClassAndItem.Rows[i]["PMA"].ToString().Trim());
                            htParams.Add("PATTERN_NO", dtMultiSaveClassAndItem.Rows[i]["PATTERN"].ToString().Trim());
                            htParams.Add("SPEC_TYPE", getSpecTypeChecked());
                            htParams.Add("SPEC_QTY", SLP_Number1.Text.Trim());
                            htParams.Add("S_START_DATE", SLP_SLPDate2.Text.Trim());
                            htParams.Add("S_END_DATE", SLP_SLPDate3.Text.Trim());
                            htParams.Add("REASON", strReason.Trim());

                            iResult = BCO.CreateMasterAndDetail(htParams, dtForUpdate, null);
                        }
                        #endregion
                    }

                    if (strErrMsgAfterChecked != "")
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ClientScript", string.Format("alert('{0}');", strErrMsgAfterChecked), true);
                    }

                    if (iResult == 0)
                    {
                        throw new Exception("新增0筆資料!");
                    }
                    else
                    {
                        if (dtForUpdate != null)
                            dtForUpdate.AcceptChanges();

                        dtDetailData = dtForUpdate;
                        dtForDetailDeleted.Clear();
                        ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "ClientScript", string.Format("alert('新增完成');location.replace('ALO081.aspx?Code=ALO08&ChanNo={0}&Store={1}');", SLP_StoreChain1.Text, SLP_Store1.Text), true);
                    }
                    #endregion
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "ClientScript", "alert('請先加入商品');", true);
            }
        }
        catch (Exception ex)
        {
            ErrorMsgLabel.Text = ex.Message;
        }
        #endregion
    }
Example #52
0
        public void Activate()
        {
            if (!MainV2.comPort.BaseStream.IsOpen)
            {
                Enabled = false;
                return;
            }
            if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduCopter2)
            {
                Enabled = true;
            }
            else
            {
                Enabled = false;
                return;
            }

            startup = true;

            changes.Clear();

            // ensure the fields are populated before setting them
            TUNE.setup(
                ParameterMetaDataRepository.GetParameterOptionsInt("TUNE", MainV2.comPort.MAV.cs.firmware.ToString())
                .ToList(), "TUNE", MainV2.comPort.MAV.param);
            CH7_OPT.setup(
                ParameterMetaDataRepository.GetParameterOptionsInt("CH7_OPT", MainV2.comPort.MAV.cs.firmware.ToString())
                .ToList(), "CH7_OPT", MainV2.comPort.MAV.param);
            CH8_OPT.setup(
                ParameterMetaDataRepository.GetParameterOptionsInt("CH8_OPT", MainV2.comPort.MAV.cs.firmware.ToString())
                .ToList(), "CH8_OPT", MainV2.comPort.MAV.param);

            TUNE_LOW.setup(0, 10000, 1000, 0.01f, "TUNE_LOW", MainV2.comPort.MAV.param);
            TUNE_HIGH.setup(0, 10000, 1000, 0.01f, "TUNE_HIGH", MainV2.comPort.MAV.param);

            HLD_LAT_P.setup(0, 0, 1, 0.001f, new[] { "HLD_LAT_P", "POS_XY_P" }, MainV2.comPort.MAV.param);
            LOITER_LAT_D.setup(0, 0, 1, 0.001f, "LOITER_LAT_D", MainV2.comPort.MAV.param);
            LOITER_LAT_I.setup(0, 0, 1, 0.001f, new[] { "LOITER_LAT_I", "VEL_XY_I" }, MainV2.comPort.MAV.param);
            LOITER_LAT_IMAX.setup(0, 0, 10, 1f, new[] { "LOITER_LAT_IMAX", "VEL_XY_IMAX" }, MainV2.comPort.MAV.param);
            LOITER_LAT_P.setup(0, 0, 1, 0.001f, new[] { "LOITER_LAT_P", "VEL_XY_P" }, MainV2.comPort.MAV.param);

            RATE_PIT_D.setup(0, 0, 1, 0.001f, new[] { "RATE_PIT_D", "ATC_RAT_PIT_D" }, MainV2.comPort.MAV.param);
            RATE_PIT_I.setup(0, 0, 1, 0.001f, new[] { "RATE_PIT_I", "ATC_RAT_PIT_I" }, MainV2.comPort.MAV.param);
            RATE_PIT_IMAX.setup(0, 0, 10, 1f, new[] { "RATE_PIT_IMAX", "ATC_RAT_PIT_IMAX" }, MainV2.comPort.MAV.param);
            RATE_PIT_P.setup(0, 0, 1, 0.001f, new[] { "RATE_PIT_P", "ATC_RAT_PIT_P" }, MainV2.comPort.MAV.param);
            RATE_PIT_FF.setup(0, 0, 1, 0.001f, "RATE_PIT_FF", MainV2.comPort.MAV.param);

            RATE_RLL_D.setup(0, 0, 1, 0.001f, new[] { "RATE_RLL_D", "ATC_RAT_RLL_D" }, MainV2.comPort.MAV.param);
            RATE_RLL_I.setup(0, 0, 1, 0.001f, new[] { "RATE_RLL_I", "ATC_RAT_RLL_I" }, MainV2.comPort.MAV.param);
            RATE_RLL_IMAX.setup(0, 0, 10, 1f, new[] { "RATE_RLL_IMAX", "ATC_RAT_RLL_IMAX" }, MainV2.comPort.MAV.param);
            RATE_RLL_P.setup(0, 0, 1, 0.001f, new[] { "RATE_RLL_P", "ATC_RAT_RLL_P" }, MainV2.comPort.MAV.param);
            RATE_RLL_FF.setup(0, 0, 1, 0.001f, "RATE_RLL_FF", MainV2.comPort.MAV.param);

            RATE_YAW_D.setup(0, 0, 1, 0.001f, new[] { "RATE_YAW_D", "ATC_RAT_YAW_D" }, MainV2.comPort.MAV.param);
            RATE_YAW_I.setup(0, 0, 1, 0.001f, new[] { "RATE_YAW_I", "ATC_RAT_YAW_I" }, MainV2.comPort.MAV.param);
            RATE_YAW_IMAX.setup(0, 0, 10, 1f, new[] { "RATE_YAW_IMAX", "ATC_RAT_YAW_IMAX" }, MainV2.comPort.MAV.param);
            RATE_YAW_P.setup(0, 0, 1, 0.001f, new[] { "RATE_YAW_P", "ATC_RAT_YAW_P" }, MainV2.comPort.MAV.param);
            RATE_YAW_FF.setup(0, 0, 1, 0.001f, "RATE_YAW_FF", MainV2.comPort.MAV.param);

            STB_PIT_P.setup(0, 0, 1, 0.001f, new[] { "STB_PIT_P", "ATC_ANG_PIT_P" }, MainV2.comPort.MAV.param);
            STB_RLL_P.setup(0, 0, 1, 0.001f, new[] { "STB_RLL_P", "ATC_ANG_RLL_P" }, MainV2.comPort.MAV.param);
            STB_YAW_P.setup(0, 0, 1, 0.001f, new[] { "STB_YAW_P", "ATC_ANG_YAW_P" }, MainV2.comPort.MAV.param);

            THR_ACCEL_D.setup(0, 0, 1, 0.001f, new[] { "THR_ACCEL_D", "ACCEL_Z_D" }, MainV2.comPort.MAV.param);
            THR_ACCEL_I.setup(0, 0, 1, 0.001f, new[] { "THR_ACCEL_I", "ACCEL_Z_I" }, MainV2.comPort.MAV.param);
            THR_ACCEL_IMAX.setup(0, 0, 10, 1f, new[] { "THR_ACCEL_IMAX", "ACCEL_Z_IMAX" }, MainV2.comPort.MAV.param);
            THR_ACCEL_P.setup(0, 0, 1, 0.001f, new[] { "THR_ACCEL_P", "ACCEL_Z_P" }, MainV2.comPort.MAV.param);
            THR_ALT_P.setup(0, 0, 1, 0.001f, new[] { "THR_ALT_P", "POS_Z_P" }, MainV2.comPort.MAV.param);
            THR_RATE_P.setup(0, 0, 1, 0.001f, new[] { "THR_RATE_P", "VEL_Z_P" }, MainV2.comPort.MAV.param);
            WPNAV_LOIT_SPEED.setup(0, 0, 1, 0.001f, "WPNAV_LOIT_SPEED", MainV2.comPort.MAV.param);
            WPNAV_RADIUS.setup(0, 0, 1, 0.001f, "WPNAV_RADIUS", MainV2.comPort.MAV.param);
            WPNAV_SPEED.setup(0, 0, 1, 0.001f, "WPNAV_SPEED", MainV2.comPort.MAV.param);
            WPNAV_SPEED_DN.setup(0, 0, 1, 0.001f, "WPNAV_SPEED_DN", MainV2.comPort.MAV.param);
            WPNAV_SPEED_UP.setup(0, 0, 1, 0.001f, "WPNAV_SPEED_UP", MainV2.comPort.MAV.param);

            // unlock entries if they differ
            if (RATE_RLL_P.Value != RATE_PIT_P.Value || RATE_RLL_I.Value != RATE_PIT_I.Value ||
                RATE_RLL_D.Value != RATE_PIT_D.Value || RATE_RLL_IMAX.Value != RATE_PIT_IMAX.Value)
            {
                CHK_lockrollpitch.Checked = false;
            }

            if (MainV2.comPort.MAV.param["H_SWASH_TYPE"] != null)
            {
                CHK_lockrollpitch.Checked = false;
            }

            startup = false;
        }
        /// <summary>
        /// Generate the Star Colleagues report
        /// </summary>
        public static void Generate(TextWriter writer, Database DB, string JournalWeightsFilename, ArrayList SetnbsToSkip, ReportsDialog ParentForm, bool WriteHeaderRow)
        {
            Reports reports = new Reports(DB, JournalWeightsFilename);

            if (WriteHeaderRow)
            {
                WriteHeaderRowToReport(writer);
            }

            // Retrieve all of the star/colleague pairs from the StarColleagues table.
            // The report is generated colleague by colleague (so that it's sorted by
            // the first column -- for the fault tolerance).
            DataTable ColleagueStarPairs = DB.ExecuteQuery("SELECT Setnb, StarSetnb FROM StarColleagues ORDER BY Setnb, StarSetnb");

            if (ColleagueStarPairs.Rows.Count == 0)
            {
                if (ParentForm != null)
                {
                    ParentForm.AddLogEntry("Unable to generate StarColleagues report: No colleagues found!");
                }
                return;
            }

            // Go through the publications and collect the counts.
            Hashtable CountsPerYear  = new Hashtable();
            Hashtable WeightsPerYear = new Hashtable();

            // Create hashtables for the four global counts for each row
            Hashtable Nbcoauth1       = new Hashtable();
            Hashtable Wghtd_Nbcoauth1 = new Hashtable();
            Hashtable Nbcoauth2       = new Hashtable();
            Hashtable Wghtd_Nbcoauth2 = new Hashtable();

            // For each star/colleague pair, produce the report rows.
            // Note that report rows are only produced for years where there
            // are collaborations.
            int Pairs = ColleagueStarPairs.Rows.Count;

            for (int Row = 0; Row < Pairs; Row++)
            {
                string Setnb     = ColleagueStarPairs.Rows[Row]["Setnb"].ToString();
                string StarSetnb = ColleagueStarPairs.Rows[Row]["StarSetnb"].ToString();

                // If this is a continuation of a previous report, SetnbsToSkip will be
                // populated with colleague Setnb values from the rows that were already
                // in the file.
                if (!SetnbsToSkip.Contains(Setnb))
                {
                    // Generate the row for the colleague

                    /*
                     * This query retrieves all of the publications that a star and colleague
                     * have in common. It takes two parameters, the star setnb and the
                     * colleague setnb, and returns all of the data necessary to produce the
                     * Star Colleagues Report rows for that star/colleague pair. It's sorted
                     * by year so that it can be processed efficiently, and so that the first
                     * and last rows in the results can be used to find the years of first and
                     * last collaboration.
                     *
                     * SELECT p.Year, p.PMID, pp.PositionType AS StarPositionType,
                     *        cp.PositionType AS ColleaguePositionType, p.Journal
                     *   FROM Publications p, ColleaguePublications cp, PeoplePublications pp
                     *  WHERE pp.Setnb = ?
                     *    AND cp.Setnb = ?
                     *    AND p.PMID = pp.PMID
                     *    AND p.PMID = cp.PMID
                     *  ORDER BY p.Year ASC
                     *
                     */

                    ArrayList Parameters = new ArrayList();
                    Parameters.Add(Database.Parameter(StarSetnb));
                    Parameters.Add(Database.Parameter(Setnb));
                    using (DataTable PubData =
                               DB.ExecuteQuery(
                                   @"SELECT p.Year, p.PMID, pp.PositionType AS StarPositionType, 
                                 cp.PositionType AS ColleaguePositionType, p.Journal
                            FROM Publications p, ColleaguePublications cp, PeoplePublications pp
                           WHERE pp.Setnb = ?
                             AND cp.Setnb = ?
                             AND p.PMID = pp.PMID
                             AND p.PMID = cp.PMID
                           ORDER BY p.Year ASC", Parameters))
                    {
                        if (PubData.Rows.Count == 0)
                        {
                            if (ParentForm != null)
                            {
                                ParentForm.AddLogEntry("No publications found for colleague " + Setnb + ", star " + StarSetnb);
                            }
                        }
                        else
                        {
                            // Get the first and last years of collaboration
                            int FirstCollabYear = Convert.ToInt32(PubData.Rows[0]["Year"]);
                            int LastCollabYear  = Convert.ToInt32(PubData.Rows[PubData.Rows.Count - 1]["Year"]);

                            // Go through the publications and collect the counts.
                            CountsPerYear.Clear();
                            WeightsPerYear.Clear();

                            // Create hashtables for the four global counts for each row
                            Nbcoauth1.Clear();
                            Wghtd_Nbcoauth1.Clear();
                            Nbcoauth2.Clear();
                            Wghtd_Nbcoauth2.Clear();

                            for (int RowNum = 0; RowNum < PubData.Rows.Count; RowNum++)
                            {
                                // Get the information about the publication from the dataset
                                DataRow PubRow = PubData.Rows[RowNum];
                                UpdateCounts(reports, PubRow, CountsPerYear, WeightsPerYear,
                                             Nbcoauth1, Wghtd_Nbcoauth1, Nbcoauth2, Wghtd_Nbcoauth2);
                            }

                            // Write the rows to the report
                            int RowsWritten = WriteReportrows(Setnb, StarSetnb, FirstCollabYear, LastCollabYear,
                                                              Nbcoauth1, Wghtd_Nbcoauth1, Nbcoauth2, Wghtd_Nbcoauth2,
                                                              writer, CountsPerYear, WeightsPerYear);

                            //ParentForm.AddLogEntry("Wrote " + RowsWritten.ToString() + " rows for colleague " + Setnb + ", star " + StarSetnb + " (" + Row.ToString() + " of " + Pairs.ToString() + ")");
                            if (ParentForm != null)
                            {
                                ParentForm.SetProgressBar(0, Pairs, Row);
                            }
                        }
                    }
                }
            }
        }
Example #54
0
        public void RefreshNowPlaying()
        {
            lock (Locker)
            {
                if (!_parent.IsConnected())
                {
                    return;
                }

                var infos = _parent.Command("GetCurrentlyPlaying");
                if (infos == null)
                {
                    return;
                }

                _currentInfo.Clear();

                foreach (var info in infos)
                {
                    var splitIndex = info.IndexOf(':') + 1;
                    if (splitIndex <= 2)
                    {
                        continue;
                    }
                    var key   = info.Substring(0, splitIndex - 1).Replace(" ", "").ToLower(CultureInfo.InvariantCulture);
                    var value = info.Substring(splitIndex, info.Length - splitIndex);
                    _currentInfo.Add(key, value);
                }
                if (GetInfo("thumb") != null)
                {
                    var thumbparts = GetInfo("thumb").Split('/');
                    var hash       = thumbparts[thumbparts.Length - 1].Trim().Replace(".tbn", "");
                    _currentInfo.Add("fanart", GetInfo("thumb").Replace("/" + hash[0] + "/", "/Fanart/"));
                }


                string[] aVolume   = null;
                string[] aProgress = null;

                if (GetInfo("playstatus") != null)
                {
                    aVolume = _parent.Command("GetVolume");
                    if (aVolume == null)
                    {
                        return;
                    }
                    aProgress = _parent.Command("GetPercentage");
                    if (aProgress == null)
                    {
                        return;
                    }
                }

                try
                {
                    _volume = aVolume != null?Convert.ToInt32("0" + aVolume[0], CultureInfo.InvariantCulture) : 0;
                }
                catch (Exception)
                {
                    _volume = 0;
                }

                _volume = Math.Min(100, _volume);
                try
                {
                    _progress = aProgress != null?Convert.ToInt32("0" + aProgress[0], CultureInfo.InvariantCulture) : 1;
                }
                catch (Exception)
                {
                    _progress = 1;
                }
                _progress = Math.Min(99, _progress);


                var nowPlaying = new ApiCurrently
                {
                    IsPlaying  = (GetInfo("playstatus") == "Playing") ? true : false,
                    IsPaused   = (GetInfo("playstatus") == "Paused") ? true : false,
                    IsNewMedia = _isNewMedia,
                    IsMuted    = (_volume == 0) ? true : false
                };

                if (GetInfo("showtitle") != null)
                {
                    nowPlaying.MediaType = "TvShow";
                }
                else if (GetInfo("title") != null)
                {
                    if (GetInfo("type") == "Audio")
                    {
                        nowPlaying.MediaType = "Audio";
                    }
                    if (GetInfo("type") == "Video")
                    {
                        nowPlaying.MediaType = "Movie";
                    }
                }
                else
                {
                    nowPlaying.MediaType = "Unknown";
                }

                nowPlaying.FileName = GetInfo("filename");
                nowPlaying.Title    = GetInfo("title");
                nowPlaying.Artist   = GetInfo("artist");
                nowPlaying.Album    = GetInfo("album");
                try
                {
                    nowPlaying.Year = Convert.ToInt32("0" + GetInfo("year"), CultureInfo.InvariantCulture);
                }
                catch
                {
                    nowPlaying.Year = 0;
                }
                try
                {
                    nowPlaying.Track = Convert.ToInt32("0" + GetInfo("track"), CultureInfo.InvariantCulture);
                }
                catch
                {
                    nowPlaying.Track = 0;
                }
                try
                {
                    nowPlaying.SeasonNumber = Convert.ToInt32("0" + GetInfo("season"), CultureInfo.InvariantCulture);
                }
                catch
                {
                    nowPlaying.SeasonNumber = 0;
                }
                try
                {
                    nowPlaying.EpisodeNumber = Convert.ToInt32("0" + GetInfo("episode"), CultureInfo.InvariantCulture);
                }
                catch
                {
                    nowPlaying.EpisodeNumber = 0;
                }

                nowPlaying.Genre     = GetInfo("genre");
                nowPlaying.ThumbURL  = GetInfo("thumb");
                nowPlaying.FanartURL = GetInfo("fanart");
                nowPlaying.ShowTitle = GetInfo("showtitle");
                nowPlaying.Plot      = GetInfo("plot");
                nowPlaying.Director  = GetInfo("director");
                nowPlaying.Volume    = GetVolume();
                nowPlaying.Progress  = GetProgress();

                nowPlaying.Studio  = GetInfo("studio");
                nowPlaying.Tagline = GetInfo("tagline");
                nowPlaying.Rating  = GetInfo("rating");

                var time = GetInfo("time");
                if (!string.IsNullOrEmpty(time))
                {
                    var splittime = time.Split(':');
                    switch (splittime.Length)
                    {
                    case 1:
                        nowPlaying.Time = new TimeSpan(0, 0, 0,
                                                       Convert.ToInt32("0" + splittime[0], CultureInfo.InvariantCulture));
                        break;

                    case 2:
                        nowPlaying.Time = new TimeSpan(0, 0,
                                                       Convert.ToInt32("0" + splittime[0], CultureInfo.InvariantCulture),
                                                       Convert.ToInt32("0" + splittime[1], CultureInfo.InvariantCulture));
                        break;

                    case 3:
                        nowPlaying.Time = new TimeSpan(0,
                                                       Convert.ToInt32("0" + splittime[0], CultureInfo.InvariantCulture),
                                                       Convert.ToInt32("0" + splittime[1], CultureInfo.InvariantCulture),
                                                       Convert.ToInt32("0" + splittime[2], CultureInfo.InvariantCulture));
                        break;

                    default:
                        nowPlaying.Time = new TimeSpan(0);
                        break;
                    }
                }

                var duration = GetInfo("duration");
                if (duration != null)
                {
                    var splitduration = duration.Split(':');
                    switch (splitduration.Length)
                    {
                    case 1:
                        nowPlaying.Duration = new TimeSpan(0, 0, 0,
                                                           Convert.ToInt32("0" + splitduration[0],
                                                                           CultureInfo.InvariantCulture));
                        break;

                    case 2:
                        nowPlaying.Duration = new TimeSpan(0, 0,
                                                           Convert.ToInt32("0" + splitduration[0],
                                                                           CultureInfo.InvariantCulture),
                                                           Convert.ToInt32("0" + splitduration[1],
                                                                           CultureInfo.InvariantCulture));
                        break;

                    case 3:
                        nowPlaying.Duration = new TimeSpan(0,
                                                           Convert.ToInt32("0" + splitduration[0],
                                                                           CultureInfo.InvariantCulture),
                                                           Convert.ToInt32("0" + splitduration[1],
                                                                           CultureInfo.InvariantCulture),
                                                           Convert.ToInt32("0" + splitduration[2],
                                                                           CultureInfo.InvariantCulture));
                        break;

                    default:
                        nowPlaying.Duration = new TimeSpan(0);
                        break;
                    }
                }

                var firstaired = GetInfo("firstaired");
                if (firstaired != null)
                {
                    var splitaired = firstaired.Split('-');
                    if (splitaired.Length > 1)
                    {
                        nowPlaying.FirstAired =
                            new DateTime(Convert.ToInt32("0" + splitaired[0], CultureInfo.InvariantCulture),
                                         Convert.ToInt32("0" + splitaired[1], CultureInfo.InvariantCulture),
                                         Convert.ToInt32("0" + splitaired[2], CultureInfo.InvariantCulture));
                    }
                }
                _nowPlaying = nowPlaying;
            }
        }
Example #55
0
        public static void TestAdd_ClearRepeatedly()
        {
            const int Iterations = 2;
            const int Count = 2;

            var hash = new Hashtable();
            for (int i = 0; i < Iterations; i++)
            {
                for (int j = 0; j < Count; j++)
                {
                    string key = "Key: i=" + i + ", j=" + j;
                    string value = "Value: i=" + i + ", j=" + j;
                    hash.Add(key, value);
                }

                Assert.Equal(Count, hash.Count);
                hash.Clear();
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get custom table id from url
        customTableId = QueryHelper.GetInteger("customtableid", 0);

        dci = DataClassInfoProvider.GetDataClassInfo(customTableId);

        // Set edited object
        EditedObject = dci;

        // If class exists and is custom table
        if ((dci != null) && dci.ClassIsCustomTable)
        {
            // Ensure that object belongs to current site or user has access to site manager
            if (!CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) && (dci.AssignedSites[SiteContext.CurrentSiteName] == null))
            {
                RedirectToInformation(GetString("general.notassigned"));
            }

            PageTitle.TitleText = GetString("customtable.data.selectdisplayedfields");
            CurrentMaster.DisplayActionsPanel = true;

            // Check 'Read' permission
            if (!dci.CheckPermissions(PermissionsEnum.Read, SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser))
            {
                ShowError(String.Format(GetString("customtable.permissiondenied.read"), dci.ClassName));
                plcContent.Visible = false;
                return;
            }

            HeaderActions.AddAction(new HeaderAction
            {
                Text = GetString("UniSelector.SelectAll"),
                OnClientClick = "ChangeFields(true); return false;",
                ButtonStyle = ButtonStyle.Default,
            });

            HeaderActions.AddAction(new HeaderAction
            {
                Text = GetString("UniSelector.DeselectAll"),
                OnClientClick = "ChangeFields(false); return false;",
                ButtonStyle = ButtonStyle.Default,
            });

            if (!RequestHelper.IsPostBack())
            {
                Hashtable reportFields = new Hashtable();

                // Get report fields
                if (!String.IsNullOrEmpty(dci.ClassShowColumns))
                {
                    reportFields.Clear();

                    foreach (string field in dci.ClassShowColumns.Split(';'))
                    {
                        // Add field key to hastable
                        reportFields[field] = null;
                    }
                }

                // Get columns names
                FormInfo fi = FormHelper.GetFormInfo(dci.ClassName, false);
                var columnNames = fi.GetColumnNames(false);

                if (columnNames != null)
                {
                    MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + dci.ClassName);
                    FormFieldInfo ffi;
                    ListItem item;
                    foreach (string name in columnNames)
                    {
                        ffi = fi.GetFormField(name);

                        // Add checkboxes to the list
                        item = new ListItem(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(GetFieldCaption(ffi, name, resolver))), name);
                        if (reportFields.Contains(name))
                        {
                            // Select checkbox if field is reported
                            item.Selected = true;
                        }
                        chkListFields.Items.Add(item);
                    }
                }
            }
        }
        else
        {
            ShowError(GetString("customtable.notcustomtable"));
            CurrentMaster.FooterContainer.Visible = false;
        }
    }
Example #57
0
        /*
         * Member Methods
         */

        protected void typeChangeRefresh()
        {
            ApplianceState state = (ApplianceState)GetApplObj();
            ComboBox       cbox  = (ComboBox)GetControl();

            try
            {
                Hashtable labels = state.Type.ValueLabels;

                /*
                 * This code may cause unneccesary flicker when displaying the
                 * ComboBox.  If it does, changes should be made here to add and
                 * remove items based upon change in the state and its dependencies.
                 */

                object stateval = state.Value;

                if (state.Type.ValueSpace is PUC.Types.EnumeratedSpace)
                {
                    PUC.Types.EnumeratedSpace espc = (PUC.Types.EnumeratedSpace)state.Type.ValueSpace;

                    //cbox.BeginUpdate();

                    cbox.Items.Clear();
                    _itemIndexMap.Clear();
                    _indexItemMap.Clear();

                    for (int i = 1; i <= espc.GetItemCount(); i++)
                    {
                        object          labelSpace = i;
                        LabelDictionary ldict      = (LabelDictionary)labels[labelSpace];

                        if (ldict.Enabled ||
                            (state.Defined && i == (int)stateval))
                        {
                            string label = ldict.GetLabelByPixelLength(cbox.Font,
                                                                       cbox.ClientSize.Width);

                            cbox.Items.Add(label);
                            _itemIndexMap[cbox.Items.Count - 1] = i;
                            _indexItemMap[i] = cbox.Items.Count - 1;

                            if (state.Defined && i == (int)stateval)
                            {
                                cbox.SelectedIndex = cbox.Items.Count - 1;
                            }
                        }
                    }


                    if (!state.Defined)
                    {
                        object          labelSpace = LabelDictionary.UndefinedToken;
                        LabelDictionary ldict      = (LabelDictionary)labels[labelSpace];

                        if (ldict != null)
                        {
                            string label = ldict.GetLabelByPixelLength(cbox.Font,
                                                                       cbox.ClientSize.Width);

                            cbox.Items.Add(label);
                            cbox.SelectedIndex = cbox.Items.Count - 1;
                        }
                    }


                    //cbox.EndUpdate();
                }
                else if (state.Type.ValueSpace is PUC.Types.BooleanSpace)
                {
                    // cbox.BeginUpdate();

                    cbox.Items.Clear();
                    _itemIndexMap.Clear();
                    _indexItemMap.Clear();
                    for (int i = 0; i < 2; i++)
                    {
                        object          labelSpace = (i == 1);
                        LabelDictionary ldict      = (LabelDictionary)labels[labelSpace];

                        if (ldict.Enabled)
                        {
                            string label = ldict.GetLabelByPixelLength(cbox.Font,
                                                                       cbox.Size.Width - MINIMUM_LEFT_PAD - MINIMUM_RIGHT_PAD);

                            cbox.Items.Add(label);
                            _itemIndexMap[cbox.Items.Count - 1] = (i == 1);
                            _indexItemMap[(i == 1)]             = cbox.Items.Count - 1;

                            if (state.Defined && (i == 1) == (bool)stateval)
                            {
                                cbox.SelectedIndex = cbox.Items.Count - 1;
                            }
                        }
                    }

                    // TODO: think of a better way to do this
                    // Currently undefined labels won't work
                    if (!state.Defined)
                    {
                        object          labelSpace = LabelDictionary.UndefinedToken;
                        LabelDictionary ldict      = (LabelDictionary)labels[labelSpace];

                        if (ldict != null)
                        {
                            string label = ldict.GetLabelByPixelLength(cbox.Font,
                                                                       cbox.ClientSize.Width);

                            cbox.Items.Add(label);
                            cbox.SelectedIndex = cbox.Items.Count - 1;
                        }
                    }


                    // cbox.EndUpdate();
                }
                else
                {
                    Globals.GetFrame(GetApplObj().Appliance)
                    .AddLogLine("SelectionListLinkedCIO does not know how to handle non-boolean/enumerated spaces");
                }
            }
            catch (Exception)
            {
                cbox.Items.Add("--");
            }
        }
Example #58
0
        /// <summary>
        /// Returns a version of a string without any HTML tags.
        /// </summary>
        /// <param name="strString">The string.</param>
        /// <returns>Version of string without HTML tags.</returns>
        public static string removeHtml
            (string strString)
        {
            // Do some common case-sensitive replacements
            Hashtable replacements = new Hashtable();

            replacements.Add("&nbsp;", " ");
            replacements.Add("&amp;", "&");
            replacements.Add("&aring;", "");
            replacements.Add("&auml;", "");
            replacements.Add("&eacute;", "");
            replacements.Add("&iacute;", "");
            replacements.Add("&igrave;", "");
            replacements.Add("&ograve;", "");
            replacements.Add("&ouml;", "");
            replacements.Add("&quot;", "\"");
            replacements.Add("&szlig;", "");
            HTMLParser parser = new HTMLParser(strString);

            foreach (string key in replacements.Keys)
            {
                string val = replacements[key] as string;
                if (strString.IndexOf(key) != -1)
                {
                    parser.replaceEveryExact(key, val);
                }
            }

            // Do some sequential replacements
            parser.replaceEveryExact("&#0", "&#");
            parser.replaceEveryExact("&#39;", "'");
            parser.replaceEveryExact("</", " <~/");
            parser.replaceEveryExact("<~/", "</");

            // Case-insensitive replacements
            replacements.Clear();
            replacements.Add("<br>", " ");
            replacements.Add("<br />", " ");
            replacements.Add("<br/>", " ");
            replacements.Add("<p>", " ");
            replacements.Add("<p />", " ");
            replacements.Add("<p/>", " ");
            foreach (string key in replacements.Keys)
            {
                string val = replacements[key] as string;
                if (strString.IndexOf(key) != -1)
                {
                    parser.replaceEvery(key, val);
                }
            }
            strString = parser.Content;

            // Remove all tags
            string strClean  = "";
            int    nIndex    = 0;
            int    nStartTag = 0;

            while ((nStartTag = strString.IndexOf("<", nIndex)) != -1)
            {
                // Extract to start of tag
                string strSubstring = strString.Substring(nIndex, (nStartTag - nIndex));
                strClean += strSubstring;
                nIndex    = nStartTag + 1;

                // Skip over tag
                int nEndTag = strString.IndexOf(">", nIndex);
                if (nEndTag == (-1))
                {
                    break;
                }
                nIndex = nEndTag + 1;
            }

            // Gather remaining text
            if (nIndex < strString.Length)
            {
                strClean += strString.Substring(nIndex, strString.Length - nIndex);
            }
            strString = strClean;
            strClean  = "";

            // Finally, reduce spaces
            parser.Content = strString;
            parser.replaceEveryExact("  ", " ");
            strString = parser.Content.Trim();

            // Return the de-HTMLized string
            return(strString);
        }
Example #59
0
        public void TestGetValues()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            Hashtable ht1 = null;

            string s1 = null;
            string s2 = null;
            string s3 = null;

            object[] objArrKeys;
            object[] objArrValues;

            ICollection icol1;
            IEnumerator ienm1;

            int i = 0;
            int iCount = 0;

            ht1 = new Hashtable();
            for (i = 0; i < 100; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                ht1.Add(s1, s2);
            }

            //
            // test Get to make sure the key-vals are accessible
            //
            for (i = 0; i < ht1.Count; i++)
            {
                sblMsg = new StringBuilder(99);
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg = new StringBuilder(99);
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                s3 = (string)ht1[s1];

                Assert.Equal(s3 , s2);
            }

            //
            // []  now GetValues and make sure every value is obtained
            //  NOTE: the keys/values obtained may not necessarily be in any order
            //
            int temp = ht1.Count;
            objArrValues = new object[temp];
                ht1.Values.CopyTo(objArrValues, 0);

                Assert.Equal(objArrValues.Length, ht1.Count);

                for (i = 0; i < objArrValues.Length; i++)
                {
                    Assert.True(ht1.ContainsValue(objArrValues[i].ToString()));
                }

            //[] Returns a collection representing the keys of this hashtable. The order in which the returned collection represents the keys is unspecified, but it is guaranteed to be the same order in which a collection returned by GetValues represents the values of the hashtable.

            int temp1 = ht1.Count;
            objArrKeys = new object[temp1];
            ht1.Keys.CopyTo(objArrKeys, 0);

            Assert.Equal(objArrKeys.Length, ht1.Count);
            for (i = 0; i < objArrKeys.Length; i++)
            {
                Assert.True(ht1.ContainsKey(objArrKeys[i].ToString()));

                // check the order of GetKeys and GetValues
                Assert.True(((string)ht1[objArrKeys[i].ToString()]).Equals(objArrValues[i].ToString()));
            }

            //[]We test other methods in the Collection to make sure that they work!!
            icol1 = ht1.Values;
            ienm1 = icol1.GetEnumerator();
            iCount = 0;
            while (ienm1.MoveNext())
            {
                iCount++;
                Assert.True(ht1.ContainsValue(ienm1.Current));
            }

            Assert.Equal(iCount, ht1.Count);
            Assert.Equal(icol1.Count, ht1.Count);
            Assert.False(icol1.IsSynchronized);
            Assert.Equal(icol1.SyncRoot, ht1.SyncRoot);

            //[] The ICollection is alive - i.e. whatever changes we do to the Underlying HT is reflected in the collection
            sblMsg = new StringBuilder();
            sblMsg.Append("key_");
            sblMsg.Append(0);
            s1 = "key_0";
            s2 = "val_0";

            ht1.Remove(s1);
            ienm1 = icol1.GetEnumerator();
            iCount = 0;
            while (ienm1.MoveNext())
            {
                s3 = (string)ienm1.Current;
                Assert.False(s3.Equals(s2));
            }

            Assert.Equal(icol1.Count, ht1.Count);

            //[] we will clear the HT and make sure that the Values are kaput
            ht1.Clear();
            Assert.Equal(0, icol1.Count);

            iCount = 0;
            ienm1 = icol1.GetEnumerator();
            while (ienm1.MoveNext())
            {
                iCount++;
            }

            Assert.Equal(0, iCount);
        }
Example #60
0
 public static void FlushParentHashtable(Hashtable table) => table?.Clear();