Example #1
0
        private void btnCast_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            System.Collections.ArrayList TestCast = new System.Collections.ArrayList();
            TestCast.Add("Test1");
            TestCast.Add("Test2");
            TestCast.Add("Test3");

            IEnumerable<string> query =
                TestCast.Cast<string>().OrderBy(n => n).Select(n => n);
            foreach (var n in query)
            {
                listBox1.Items.Add("Cast : " + n);
            }

            int[] numbers = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
            string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

            var textNums = from n in numbers
                           select strings[n];

            foreach (var n in textNums)
            {
                listBox1.Items.Add("Select : " + n);
            }
        }
        static void Main()
        {
            int totalCount;
            System.Collections.ArrayList list =
                new System.Collections.ArrayList();

            Console.Write("Enter a number between 2 and 1000:");
            totalCount = int.Parse(Console.ReadLine());

            // Execution-time error:
            // list.Add(0);  // Cast to double or 'D' suffix required.
                             // Whether cast or using 'D' suffix,
                             // CIL is identical.
            list.Add((double)0);
            list.Add((double)1);
            for(int count = 2; count < totalCount; count++)
            {
                list.Add(
                    ((double)list[count - 1] +
                    (double)list[count - 2]));
            }

            foreach(double count in list)
            {
                Console.Write("{0}, ", count);
            }
        }
Example #3
0
        public override System.Collections.ArrayList GeneratePoints(EPoint ptStart)
        {
            //Calculate curve's control and end anchor points:
            //Control point is the start point + offset to control
            EPoint ptControl = ptStart + this._ptControl;
            //End point is control point + offset to anchor:
            EPoint ptAnchor = ptControl + this._ptAnchor;

            //now calculate two bezier handles for the curve (Flash uses quadratic beziers, GDI+ uses cubic).
            //The two handles are 2/3rds from each endpoint to the control point.
            EPointF diff = (ptControl-ptStart).ToEPointF();
            EPointF ctrl1 = EPointF.FromLengthAndAngle(diff.Length*2/3, diff.Angle) + ptStart.ToEPointF();
            //EPointF ctrl1 = ptStart.ToEPointF() + diff/2f;
            //EPointF ctrl1 = new EPointF(ptStart.X + (1f * (ptControl.X - ptStart.X) / 2f), ptStart.Y + (1f * (ptControl.Y - ptStart.Y) / 2f));

            diff = (ptControl-ptAnchor).ToEPointF();
            EPointF ctrl2 = EPointF.FromLengthAndAngle(diff.Length*2/3, diff.Angle) + ptAnchor.ToEPointF();
            //diff = (ptAnchor-ptControl).ToEPointF();
            //EPointF ctrl2 = ptControl.ToEPointF() + diff/2f;
            //ctrl2 = new EPointF(ptControl.X + (1f * (ptAnchor.X - ptControl.X) / 2f), ptControl.Y + (1f * (ptAnchor.Y - ptControl.Y) / 2f));

            System.Collections.ArrayList pts = new System.Collections.ArrayList();
            pts.Add(ptStart.ToEPointF());
            pts.Add(ctrl1);
            pts.Add(ctrl2);
            pts.Add(ptAnchor.ToEPointF());
            return pts;
        }
 public MultiFormatOneDReader(System.Collections.Hashtable hints)
 {
     System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS];
     readers = new System.Collections.ArrayList();
     if (possibleFormats != null) {
       if (possibleFormats.Contains(BarcodeFormat.EAN_13) ||
           possibleFormats.Contains(BarcodeFormat.UPC_A) ||
           possibleFormats.Contains(BarcodeFormat.EAN_8) ||
           possibleFormats.Contains(BarcodeFormat.UPC_E))
       {
         readers.Add(new MultiFormatUPCEANReader(hints));
       }
       if (possibleFormats.Contains(BarcodeFormat.CODE_39)) {
           readers.Add(new Code39Reader());
       }
       if (possibleFormats.Contains(BarcodeFormat.CODE_128))
       {
           readers.Add(new Code128Reader());
       }
       if (possibleFormats.Contains(BarcodeFormat.ITF))
       {
           readers.Add(new ITFReader());
       }
     }
     if (readers.Count==0) {
         readers.Contains(new MultiFormatUPCEANReader(hints));
         readers.Contains(new Code39Reader());
         readers.Contains(new Code128Reader());
       // TODO: Add ITFReader once it is validated as production ready, and tested for performance.
       //readers.addElement(new ITFReader());
     }
 }
        public void summaryInit()
        {
            //*** cb***
            //Refer C:\Users\suandich\Downloads\DragAndDropListView_demo\Form1.cs
            SummaryMainClass sm = new SummaryMainClass();
            DataTable dtRaw = sm.RawData();
            for (int i = 0; i < dtRaw.Columns.Count; i++)
            {
                System.Diagnostics.Debug.Write(sm.dt.Columns[i].ToString() + " | ");
                listView1.Items.Add(sm.dt.Columns[i].ToString());
            }

            string[] Rowfield = new string[listView3.Items.Count];
            listView3.Items.CopyTo(Rowfield, 0);

            string[] Columnfield = new string[listView2.Items.Count];
            listView2.Items.CopyTo(Columnfield, 0);

            string[] Datafield = new string[listView4.Items.Count];
            listView4.Items.CopyTo(Datafield, 0);

            System.Collections.ArrayList list = new System.Collections.ArrayList();
            list.Add("Cat");
            list.Add("Zebra");
            list.Add("Dog");
            list.Add("Cow");

            DataTable dtSum = sm.SummaryData("",Rowfield,Columnfield);
            dataGridView1.DataSource = dtSum.DefaultView;
        }
Example #6
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="p_To">null if not used</param>
		/// <param name="p_Cc">null if not used</param>
		/// <param name="p_Bcc">null if not used</param>
		/// <param name="p_Subject">null if not used</param>
		/// <param name="p_Body">null if not used</param>
		/// <returns></returns>
		public static string FormatMailToCommand(string[] p_To, string[] p_Cc, string[] p_Bcc, string p_Subject, string p_Body)
		{
			string l_To = FormatEMailAddress(p_To);
			string l_CC = FormatEMailAddress(p_Cc);
			string l_Bcc = FormatEMailAddress(p_Bcc);
				
			string l_Command = "mailto:";
			if (l_To!=null)
				l_Command+=l_To;

			System.Collections.ArrayList l_Parameters = new System.Collections.ArrayList();

			if (l_CC!=null)
				l_Parameters.Add("CC="+l_CC);
			if (l_Bcc!=null)
				l_Parameters.Add("BCC="+l_Bcc);
			if (p_Subject!=null)
				l_Parameters.Add("subject="+p_Subject);
			if (p_Body!=null)
				l_Parameters.Add("body="+p_Body);

			if (l_Parameters.Count>0)
			{
				string[] l_tmp = new string[l_Parameters.Count];
				l_Parameters.CopyTo(l_tmp,0);
				l_Command+="?";
				l_Command+=string.Join("&",l_tmp);
			}

			return l_Command;
		}
Example #7
0
        static void Main(string[] args)
        {
            Toy doll = new Toy();
            doll.Make = "rubber";
            doll.Model = "barbie";
            doll.Name = "Elsa";

            Toy car = new Toy();
            car.Make = "plastic";
            car.Model = "BMW";
            car.Name = "SPUR";

            System.Collections.ArrayList myArrayList = new System.Collections.ArrayList();
            myArrayList.Add(doll);
            myArrayList.Add(car);

            System.Collections.Specialized.ListDictionary myDictionary
                = new System.Collections.Specialized.ListDictionary();

            myDictionary.Add(doll.Name, doll);
            myDictionary.Add(car.Name, car);
            foreach (object o in myArrayList)
            {
                Console.WriteLine(((Toy)o).Name);
            }

            Console.WriteLine(((Toy)myDictionary["Elsa"]).Model);
            Console.ReadLine();
        }
Example #8
0
 public override System.Collections.ArrayList GeneratePoints(EPoint ptStart)
 {
     System.Collections.ArrayList pts = new System.Collections.ArrayList();
     EPoint ptEnd = ptStart + this._ptTarget;
     pts.Add(ptStart);
     pts.Add(ptEnd);
     return pts;
 }
Example #9
0
        public AdaptiveLookback(Bars bars, int howManySwings, bool UseAll, string description)
            : base(bars, description)
        {
            this.bars = bars;

            bool SwingLo, SwingHi;
            double lastSL = bars.Low[1];
            double lastSH = bars.High[1];
            int firstSwingBarOnChart = 0;
            int lastSwingInCalc = 0;
            int swingCount = 0;
            DataSeries so = new DataSeries(bars.Close, "swing_oscillator");
            System.Collections.ArrayList SwingBarArray = new System.Collections.ArrayList();

            for (int bar = 5; bar < bars.Count; bar++)
            {
                SwingLo = (CumDown.Series(bars.Low, 1)[bar - 2] >= 2) &&
                    (CumUp.Series(bars.High, 1)[bar] == 2);
                SwingHi = (CumUp.Series(bars.High, 1)[bar - 2] >= 2) &&
                    (CumDown.Series(bars.Low, 1)[bar] == 2);

                if (SwingLo)
                    so[bar] = -1;
                else
                    if (SwingHi)
                        so[bar] = 1;
                    else
                        so[bar] = 0;

                if ((so[bar] != 0) & (swingCount == 0))
                {
                    firstSwingBarOnChart = bar;
                    swingCount++;
                    SwingBarArray.Add(bar);
                }
                else
                    if (swingCount > 0)
                    {
                        if (so[bar] != 0.0)
                        {
                            swingCount++;
                            SwingBarArray.Add(bar);
                        }

                        // 20090127 Added
                        if (swingCount == howManySwings)
                            base.FirstValidValue = bar;
                    }

                lastSwingInCalc = (SwingBarArray.Count - howManySwings);

                if (lastSwingInCalc >= 0)
                {
                    base[bar] = UseAll ? (int)(bars.Count / SwingBarArray.Count) :
                        (bar - (int)SwingBarArray[lastSwingInCalc]) / howManySwings;
                }
            }
        }
Example #10
0
        private void cmdSaveAll_Click(object sender, EventArgs e)
        {
            if (!System.IO.File.Exists(txtFile.Text))
            {
                MessageBox.Show("File is not exist.");
                return;
            }

            System.Collections.ArrayList suffixs = new System.Collections.ArrayList();
            suffixs.Add("");

            if (chkFlip.Checked) suffixs.Add("f");
            if (this.chkSel.Checked) suffixs.Add("s");
            if (chkFlip.Checked && chkSel.Checked) suffixs.Add("sf");

            System.IO.FileInfo fi = new System.IO.FileInfo(txtFile.Text);
            System.IO.FileInfo[] fis = fi.Directory.GetFiles("*.bmp", System.IO.SearchOption.TopDirectoryOnly);

            string ext = "";
            System.Drawing.Imaging.ImageFormat imgFormat = null;
            if (optGif.Checked)
            {
                ext = "gif";
                imgFormat = System.Drawing.Imaging.ImageFormat.Gif;
            }
            else if (optPng.Checked)
            {
                ext = "png";
                imgFormat = System.Drawing.Imaging.ImageFormat.Png;
            }

            foreach (System.IO.FileInfo fi2 in fis)
            {
                foreach (string suffix in suffixs)
                {
                    Bitmap bmp = null;
                    if (suffix == "f")
                        bmp = ConvertBitmap(fi2.FullName, true, false);
                    else if (suffix == "s")
                        bmp = ConvertBitmap(fi2.FullName, false, true);
                    else if (suffix == "sf")
                        bmp = ConvertBitmap(fi2.FullName, true, true);
                    else
                        bmp = ConvertBitmap(fi2.FullName, false, false);

                    string fileName = string.Format(@"{0}\{1}{2}.{3}", fi2.DirectoryName,
                        fi2.Name.Substring(0, fi2.Name.Length - fi2.Extension.Length),
                        suffix, ext);

                    if (System.IO.File.Exists(fileName)) System.IO.File.Delete(fileName);

                    bmp.Save(fileName, imgFormat);
                }
            }

            MessageBox.Show("Done");
        }
		private string[] GetAvailableDestinationTables()
		{
			System.Collections.ArrayList result = new System.Collections.ArrayList();
			result.Add("New table");
			foreach (Altaxo.Data.DataTable table in Current.Project.DataTableCollection)
				result.Add(table.Name);

			return (string[])result.ToArray(typeof(string));
		}
		/// <summary> <p>Creates skeletal source code (without correct data structure but no business
		/// logic) for all data types found in the normative database.  For versions > 2.2, Primitive data types
		/// are not generated, because they are coded manually (as of HAPI 0.3).  
		/// </summary>
		public static void  makeAll(System.String baseDirectory, System.String version)
		{
			//make base directory
			if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
			{
				baseDirectory = baseDirectory + "/";
			}
			System.IO.FileInfo targetDir = NuGenSourceGenerator.makeDirectory(baseDirectory + NuGenSourceGenerator.getVersionPackagePath(version) + "datatype");
			
			//get list of data types
			System.Collections.ArrayList types = new System.Collections.ArrayList();
			System.Data.OleDb.OleDbConnection conn = NuGenNormativeDatabase.Instance.Connection;
			System.Data.OleDb.OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
			//get normal data types ... 
			System.Data.OleDb.OleDbCommand temp_OleDbCommand;
			temp_OleDbCommand = stmt;
			temp_OleDbCommand.CommandText = "select data_type_code from HL7DataTypes, HL7Versions where HL7Versions.version_id = HL7DataTypes.version_id and HL7Versions.hl7_version = '" + version + "'";
			System.Data.OleDb.OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();
			while (rs.Read())
			{
				types.Add(System.Convert.ToString(rs[1 - 1]));
			}
			
			//get CF, CK, CM, CN, CQ sub-types ... 
			
			System.Data.OleDb.OleDbCommand temp_OleDbCommand2;
			temp_OleDbCommand2 = stmt;
			temp_OleDbCommand2.CommandText = "select data_structure from HL7DataStructures, HL7Versions where (" + "data_type_code  = 'CF' or " + "data_type_code  = 'CK' or " + "data_type_code  = 'CM' or " + "data_type_code  = 'CN' or " + "data_type_code  = 'CQ') and " + "HL7Versions.version_id = HL7DataStructures.version_id and  HL7Versions.hl7_version = '" + version + "'";
			rs = temp_OleDbCommand2.ExecuteReader();
			while (rs.Read())
			{
				types.Add(System.Convert.ToString(rs[1 - 1]));
			}
			
			NuGenNormativeDatabase.Instance.returnConnection(conn);
			
			System.Console.Out.WriteLine("Generating " + types.Count + " datatypes for version " + version);
			if (types.Count == 0)
			{
			}
			
			for (int i = 0; i < types.Count; i++)
			{
				try
				{
					make(targetDir, (System.String) types[i], version);
				}
				catch (DataTypeException)
				{
				}
				catch (System.Exception)
				{
				}
			}
		}
        public StartUIACacheRequestCommand()
        {
            System.Collections.ArrayList defaultPropertiesList =
                new System.Collections.ArrayList();
            defaultPropertiesList.Add("Name");
            defaultPropertiesList.Add("AutomationId");
            defaultPropertiesList.Add("ClassName");
            defaultPropertiesList.Add("ControlType");
            defaultPropertiesList.Add("NativeWindowHandle");
            defaultPropertiesList.Add("BoundingRectangle");
            defaultPropertiesList.Add("ClickablePoint");
            defaultPropertiesList.Add("IsEnabled");
            defaultPropertiesList.Add("IsOffscreen");
            this.Property = (string[])defaultPropertiesList.ToArray(typeof(string));

            System.Collections.ArrayList defaultPatternsList =
                new System.Collections.ArrayList();
            defaultPatternsList.Add("ExpandCollapsePattern");
            defaultPatternsList.Add("InvokePattern");
            defaultPatternsList.Add("ScrollItemPattern");
            defaultPatternsList.Add("SelectionItemPattern");
            defaultPatternsList.Add("SelectionPattern");
            defaultPatternsList.Add("TextPattern");
            defaultPatternsList.Add("TogglePattern");
            defaultPatternsList.Add("ValuePattern");
            this.Pattern = (string[])defaultPatternsList.ToArray(typeof(string));

            this.Scope = "SUBTREE";

            this.Filter = "RAW";
        }
Example #14
0
		/// <exception cref="System.Exception"></exception>
		public virtual void Test2()
		{
			string baseName = GetBaseName();
			NeoDatis.Odb.ODB odb = Open(baseName);
			long nbFunctions = odb.Count(new NeoDatis.Odb.Impl.Core.Query.Criteria.CriteriaQuery
				(typeof(NeoDatis.Odb.Test.VO.Login.Function)));
			long nbProfiles = odb.Count(new NeoDatis.Odb.Impl.Core.Query.Criteria.CriteriaQuery
				(typeof(NeoDatis.Odb.Test.VO.Login.Profile)));
			NeoDatis.Odb.Test.VO.Login.Function function1 = new NeoDatis.Odb.Test.VO.Login.Function
				("function1");
			NeoDatis.Odb.Test.VO.Login.Function function2 = new NeoDatis.Odb.Test.VO.Login.Function
				("function2");
			NeoDatis.Odb.Test.VO.Login.Function function3 = new NeoDatis.Odb.Test.VO.Login.Function
				("function3");
			System.Collections.IList functions = new System.Collections.ArrayList();
			functions.Add(function1);
			functions.Add(function2);
			functions.Add(function3);
			NeoDatis.Odb.Test.VO.Login.Profile profile1 = new NeoDatis.Odb.Test.VO.Login.Profile
				("profile1", functions);
			NeoDatis.Odb.Test.VO.Login.Profile profile2 = new NeoDatis.Odb.Test.VO.Login.Profile
				("profile2", function1);
			odb.Store(profile1);
			odb.Store(profile2);
			odb.Close();
			odb = Open(baseName);
			// checks functions
			NeoDatis.Odb.Objects lfunctions = odb.GetObjects(typeof(NeoDatis.Odb.Test.VO.Login.Function
				), true);
			AssertEquals(nbFunctions + 3, lfunctions.Count);
			NeoDatis.Odb.Objects l = odb.GetObjects(new NeoDatis.Odb.Impl.Core.Query.Criteria.CriteriaQuery
				(typeof(NeoDatis.Odb.Test.VO.Login.Function), NeoDatis.Odb.Core.Query.Criteria.Where
				.Equal("name", "function2")));
			NeoDatis.Odb.Test.VO.Login.Function function = (NeoDatis.Odb.Test.VO.Login.Function
				)l.GetFirst();
			odb.Delete(function);
			odb.Close();
			odb = Open(baseName);
			AssertEquals(nbFunctions + 2, odb.Count(new NeoDatis.Odb.Impl.Core.Query.Criteria.CriteriaQuery
				(typeof(NeoDatis.Odb.Test.VO.Login.Function))));
			NeoDatis.Odb.Objects l2 = odb.GetObjects(typeof(NeoDatis.Odb.Test.VO.Login.Function
				), true);
			// check Profile 1
			NeoDatis.Odb.Objects lprofile = odb.GetObjects(new NeoDatis.Odb.Impl.Core.Query.Criteria.CriteriaQuery
				(typeof(NeoDatis.Odb.Test.VO.Login.Profile), NeoDatis.Odb.Core.Query.Criteria.Where
				.Equal("name", "profile1")));
			NeoDatis.Odb.Test.VO.Login.Profile p1 = (NeoDatis.Odb.Test.VO.Login.Profile)lprofile
				.GetFirst();
			AssertEquals(2, p1.GetFunctions().Count);
			odb.Close();
			DeleteBase(baseName);
		}
Example #15
0
        public virtual void TestSubListJava()
		{
			System.Collections.IList l = new System.Collections.ArrayList();
			l.Add("param1");
			l.Add("param2");
			l.Add("param3");
			l.Add("param4");
			int fromIndex = 1;
			int size = 2;
			int endIndex = fromIndex + size;
			System.Collections.IList l2 = l.SubList(fromIndex, endIndex);
			AssertEquals(2, l2.Count);
		}
        private void button30_Click(object sender, EventArgs e)
        {
            System.Collections.ArrayList arrList = new System.Collections.ArrayList();

            arrList.Add(new Point(100, 100));
            arrList.Add(new Point(100, 100));

            //((Point) arrList[0]).X

            var q = from p in arrList.Cast<Point>()
                    select p;

            this.dataGridView1.DataSource = q.ToList();
        }
		public MultiFormatOneDReader(System.Collections.Hashtable hints)
		{
			System.Collections.ArrayList possibleFormats = hints == null?null:(System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS];
			bool useCode39CheckDigit = hints != null && hints[DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT] != null;
			readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
			if (possibleFormats != null)
			{
				if (possibleFormats.Contains(BarcodeFormat.EAN_13) || possibleFormats.Contains(BarcodeFormat.UPC_A) || possibleFormats.Contains(BarcodeFormat.EAN_8) || possibleFormats.Contains(BarcodeFormat.UPC_E))
				{
					readers.Add(new MultiFormatUPCEANReader(hints));
				}
				if (possibleFormats.Contains(BarcodeFormat.CODE_39))
				{
					readers.Add(new Code39Reader(useCode39CheckDigit));
				}
				if (possibleFormats.Contains(BarcodeFormat.CODE_128))
				{
					readers.Add(new Code128Reader());
				}
				if (possibleFormats.Contains(BarcodeFormat.ITF))
				{
					readers.Add(new ITFReader());
				}
			}
			if ((readers.Count == 0))
			{
				readers.Add(new MultiFormatUPCEANReader(hints));
				readers.Add(new Code39Reader());
				readers.Add(new Code128Reader());
				readers.Add(new ITFReader());
			}
		}
Example #18
0
		private object GetUserInstance(int i)
		{
			NeoDatis.Odb.Test.VO.Login.Function login = new NeoDatis.Odb.Test.VO.Login.Function
				("login" + i);
			NeoDatis.Odb.Test.VO.Login.Function logout = new NeoDatis.Odb.Test.VO.Login.Function
				("logout" + i);
			System.Collections.IList list = new System.Collections.ArrayList();
			list.Add(login);
			list.Add(logout);
			NeoDatis.Odb.Test.VO.Login.Profile profile = new NeoDatis.Odb.Test.VO.Login.Profile
				("operator" + i, list);
			NeoDatis.Odb.Test.VO.Login.User user = new NeoDatis.Odb.Test.VO.Login.User("olivier smadja"
				 + i, "*****@*****.**", profile);
			return user;
		}
 /**************************************************�ַ��������㷨**************************************************/
 public static string DecryptString(string str)
 {
     if ((str.Length % 4) != 0)
     {
         throw new ArgumentException("������ȷ��BASE64���룬���顣", "str");
     }
     if (!System.Text.RegularExpressions.Regex.IsMatch(str, "^[A-Z0-9/+=]*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
     {
         throw new ArgumentException("��������ȷ��BASE64���룬���顣", "str");
     }
     string Base64Code = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=";
     int page = str.Length / 4;
     System.Collections.ArrayList outMessage = new System.Collections.ArrayList(page * 3);
     char[] message = str.ToCharArray();
     for (int i = 0; i < page; i++)
     {
         byte[] instr = new byte[4];
         instr[0] = (byte)Base64Code.IndexOf(message[i * 4]);
         instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]);
         instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]);
         instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]);
         byte[] outstr = new byte[3];
         outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
         if (instr[2] != 64)
         {
             outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
         }
         else
         {
             outstr[2] = 0;
         }
         if (instr[3] != 64)
         {
             outstr[2] = (byte)((instr[2] << 6) ^ instr[3]);
         }
         else
         {
             outstr[2] = 0;
         }
         outMessage.Add(outstr[0]);
         if (outstr[1] != 0)
             outMessage.Add(outstr[1]);
         if (outstr[2] != 0)
             outMessage.Add(outstr[2]);
     }
     byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte"));
     return System.Text.Encoding.Default.GetString(outbyte);
 }
Example #20
0
        public void fillData()
        {
            int idGDV = int.Parse(Request.Cookies["MaGDV"].Value);

            DataTable dt = daoNews.GetListByGDV(idGDV);
            PagedDataSource pgitems = new PagedDataSource();
            System.Data.DataView dv = new System.Data.DataView(dt);
            pgitems.DataSource = dv;
            pgitems.AllowPaging = true;
            pgitems.PageSize = 20;
            if (PageNumber >= pgitems.PageCount) PageNumber = 0;
            pgitems.CurrentPageIndex = PageNumber;
            if (pgitems.PageCount > 1)
            {
                rptPages.Visible = true;
                System.Collections.ArrayList pages = new System.Collections.ArrayList();
                for (int i = 0; i < pgitems.PageCount; i++)
                    pages.Add((i + 1).ToString());
                rptPages.DataSource = pages;
                rptPages.DataBind();
            }
            else
                rptPages.Visible = false;

            repeaterList.DataSource = pgitems;
            repeaterList.DataBind();
        }
 protected void LoadData()
 {
     QuiTrinhDAO qtdao = new QuiTrinhDAO();
     DataTable dt = new DataTable();
     dt = qtdao.DSQuiTrinh();
     PagedDataSource pgitems = new PagedDataSource();
     System.Data.DataView dv = new System.Data.DataView(dt);
     pgitems.DataSource = dv;
     pgitems.AllowPaging = true;
     pgitems.PageSize = 15;
     pgitems.CurrentPageIndex = PageNumber;
     if (pgitems.PageCount > 1)
     {
         rptPages.Visible = true;
         System.Collections.ArrayList pages = new System.Collections.ArrayList();
         for (int i = 0; i < pgitems.PageCount; i++)
             pages.Add((i + 1).ToString());
         rptPages.DataSource = pages;
         rptPages.DataBind();
     }
     else
         rptPages.Visible = false;
     rpTinTuc.DataSource = pgitems;
     rpTinTuc.DataBind();
 }
Example #22
0
        public virtual void  SetUp()
		{
			workDir = new System.IO.FileInfo(System.Configuration.ConfigurationSettings.AppSettings.Get("tempDir") + "\\" + "TestDoc");
			System.IO.Directory.CreateDirectory(workDir.FullName);
			
			indexDir = new System.IO.FileInfo(workDir.FullName + "\\" + "testIndex");
			System.IO.Directory.CreateDirectory(indexDir.FullName);
			
			Directory directory = FSDirectory.GetDirectory(indexDir, true);
			directory.Close();
			
			files = new System.Collections.ArrayList();
			files.Add(CreateFile("test.txt", "This is the first test file"));
			
			files.Add(CreateFile("test2.txt", "This is the second test file"));
		}
		public QueryTermVector(System.String queryString, Analyzer analyzer)
		{
			if (analyzer != null)
			{
				TokenStream stream = analyzer.TokenStream("", new System.IO.StringReader(queryString));
				if (stream != null)
				{
					System.Collections.ArrayList terms = new System.Collections.ArrayList();
					try
					{
						bool hasMoreTokens = false;
						
						stream.Reset();
						TermAttribute termAtt = (TermAttribute) stream.AddAttribute(typeof(TermAttribute));
						
						hasMoreTokens = stream.IncrementToken();
						while (hasMoreTokens)
						{
							terms.Add(termAtt.Term());
							hasMoreTokens = stream.IncrementToken();
						}
						ProcessTerms((System.String[]) terms.ToArray(typeof(System.String)));
					}
					catch (System.IO.IOException e)
					{
					}
				}
			}
		}
Example #24
0
        public void fillData()
        {
            DataTable dt = newsDao.GetListSearchByYearMonth(year, month);
            PagedDataSource pgitems = new PagedDataSource();
            System.Data.DataView dv = new System.Data.DataView(dt);
            pgitems.DataSource = dv;
            pgitems.AllowPaging = true;
            pgitems.PageSize = 20;
            if (PageNumber >= pgitems.PageCount) PageNumber = 0;
            pgitems.CurrentPageIndex = PageNumber;
            if (pgitems.PageCount > 1)
            {
                rptPages.Visible = true;
                System.Collections.ArrayList pages = new System.Collections.ArrayList();
                for (int i = 0; i < pgitems.PageCount; i++)
                    pages.Add((i + 1).ToString());
                rptPages.DataSource = pages;
                rptPages.DataBind();
            }
            else
                rptPages.Visible = false;

            repeaterList.DataSource = pgitems;
            repeaterList.DataBind();
        }
		/// <summary> Given a string that contains HL7 messages, and possibly other junk, 
		/// returns an array of the HL7 messages.  
		/// An attempt is made to recognize segments even if there is other 
		/// content between segments, for example if a log file logs segments 
		/// individually with timestamps between them.  
		/// 
		/// </summary>
		/// <param name="theSource">a string containing HL7 messages 
		/// </param>
		/// <returns> the HL7 messages contained in theSource
		/// </returns>
        private static System.String[] getHL7Messages(System.String theSource)
        {
            System.Collections.ArrayList messages = new System.Collections.ArrayList(20);
            Match startMatch = new Regex("^MSH", RegexOptions.Multiline).Match(theSource);

            foreach (Group group in startMatch.Groups)
            {
                System.String messageExtent = getMessageExtent(theSource.Substring(group.Index), "^MSH");

                char fieldDelim = messageExtent[3];

                Match segmentMatch = Regex.Match(messageExtent, "^[A-Z]{3}\\" + fieldDelim + ".*$", RegexOptions.Multiline);

                System.Text.StringBuilder msg = new System.Text.StringBuilder();
                foreach (Group segGroup in segmentMatch.Groups)
                {
                    msg.Append(segGroup.Value.Trim());
                    msg.Append('\r');
                }

                messages.Add(msg.ToString());
            }

            String[] retVal = new String[messages.Count];
            messages.CopyTo(retVal);

            return retVal;
        }
	private static void InitXR()
	{
		try
		{
			string FILEP = "file:\\";
			string EXT = "-netz.resources";
			string path = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
			if(path.StartsWith(FILEP)) path = path.Substring(FILEP.Length, path.Length - FILEP.Length);
			string[] files = Directory.GetFiles(path, "*" + EXT);
			if((files != null) && (files.Length > 0))
			{
				xrRm = new System.Collections.ArrayList();
				for(int i = 0; i < files.Length; i++)
				{
					string name = Path.GetFileName(files[i]);
					name = name.Substring(0, name.Length - EXT.Length);
					ResourceManager temp = ResourceManager.CreateFileBasedResourceManager(name + "-netz", path, null);
					if(temp != null)
					{
						xrRm.Add(temp);
					}
				}
			}
		}catch
		{
			// fail silently here if something bad with regard to permissions happens
		}
	}
Example #27
0
		public virtual void  SetUp()
		{
			workDir = new System.IO.FileInfo(System.IO.Path.Combine(SupportClass.AppSettings.Get("tempDir", "tempDir"), "TestDoc"));
			System.IO.Directory.CreateDirectory(workDir.FullName);
			
			indexDir = new System.IO.FileInfo(System.IO.Path.Combine(workDir.FullName, "testIndex"));
			System.IO.Directory.CreateDirectory(indexDir.FullName);
			
			Directory directory = FSDirectory.GetDirectory(indexDir, true);
			directory.Close();
			
			files = new System.Collections.ArrayList();
			files.Add(CreateOutput("test.txt", "This is the first test file"));
			
			files.Add(CreateOutput("test2.txt", "This is the second test file"));
		}
 private int insertToDB()
 {
     DTO.Invoice invoice = new DTO.Invoice();
     System.Collections.ArrayList details = new System.Collections.ArrayList();
     for (int i = 0; i < grdItems.Rows.Count; i++)
     {
         DTO.InvoiceDetail d = new DTO.InvoiceDetail();
         DTO.Product p = new DTO.Product();
         p.Productid = int.Parse(grdItems.Rows[i].Cells[7].Value.ToString());
         d.Quantity = int.Parse(grdItems.Rows[i].Cells[2].Value.ToString());
         d.Priceout = decimal.Parse(grdItems.Rows[i].Cells[3].Value.ToString());
         d.Dicount = decimal.Parse(grdItems.Rows[i].Cells[4].Value.ToString());
         d.Pricein = decimal.Parse(grdItems.Rows[i].Cells[8].Value.ToString());
         d.Product = p;
         details.Add(d);
     }
     
     DTO.Member member = new DTO.Member();
     member.Memberid = (int)cboMember.SelectedValue;            ///
     invoice.Staff = UserSession.Session.Staff;
     invoice.Member = member;
     invoice.Remark = "";
     invoice.Discount = decimal.Parse(txtDiscount.Text.Replace("%", "").Replace(" ",""));
     invoice.InvoiceDetail = details;
     return new DAO.InvoiceDAO().addInvoice(invoice);
 }
Example #29
0
        public void loadComment(int idNews)
        {
            DataTable dt = daoNews.GetListComment(idNews);
            PagedDataSource pgitems = new PagedDataSource();
            System.Data.DataView dv = new System.Data.DataView(dt);
            pgitems.DataSource = dv;
            pgitems.AllowPaging = true;
            pgitems.PageSize = 20;
            if (PageNumber >= pgitems.PageCount) PageNumber = 0;
            pgitems.CurrentPageIndex = PageNumber;
            if (pgitems.PageCount > 1)
            {
                rptPagesComment.Visible = true;
                System.Collections.ArrayList pages = new System.Collections.ArrayList();
                for (int i = 0; i < pgitems.PageCount; i++)
                    pages.Add((i + 1).ToString());
                rptPagesComment.DataSource = pages;
                rptPagesComment.DataBind();
            }
            else
                rptPagesComment.Visible = false;

            rptComment.DataSource = pgitems;
            rptComment.DataBind();

            lblNumberComment.Text = "("+ dt.Rows.Count +")";
        }
Example #30
0
 /// <summary>
 /// Performs a pathping
 /// </summary>
 /// <param name="ipaTarget">The target</param>
 /// <param name="iHopcount">The maximum hopcount</param>
 /// <param name="iTimeout">The timeout for each ping</param>
 /// <returns>An array of PingReplys for the whole path</returns>
 public static PingReply[] PerformPathping(IPAddress ipaTarget, int iHopcount, int iTimeout)
 {
     System.Collections.ArrayList arlPingReply = new System.Collections.ArrayList();
     Ping myPing = new Ping();
     PingReply prResult = null;
     int iTimeOutCnt = 0;
     for (int iC1 = 1; iC1 < iHopcount && iTimeOutCnt<5; iC1++)
     {
         prResult = myPing.Send(ipaTarget, iTimeout, new byte[10], new PingOptions(iC1, false));
         if (prResult.Status == IPStatus.Success)
         {
             iC1 = iHopcount;
             iTimeOutCnt = 0;
         }
         else if (prResult.Status == IPStatus.TtlExpired)
         {
             iTimeOutCnt = 0;
         }
         else if (prResult.Status == IPStatus.TimedOut)
         {
             iTimeOutCnt++;
         }
         arlPingReply.Add(prResult);
     }
     PingReply[] prReturnValue = new PingReply[arlPingReply.Count];
     for (int iC1 = 0; iC1 < arlPingReply.Count; iC1++)
     {
         prReturnValue[iC1] = (PingReply)arlPingReply[iC1];
     }
     return prReturnValue;
 }
Example #31
0
        /// <summary>
        /// 保存
        /// </summary>
        private void btnSave()
        {
            try
            {
                gridView1.FocusedRowHandle -= 1;
                gridView1.FocusedRowHandle += 1;
            }
            catch { }

            string s调拨单号 = "";
            string sErr  = "";
            int    iCou  = 0;

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                if (!Convert.ToBoolean(gridView1.GetRowCellValue(i, gridColiChk)))
                {
                    continue;
                }
                if (gridView1.GetRowCellValue(i, gridCol调出仓库) == null || gridView1.GetRowCellValue(i, gridCol调出仓库).ToString().Trim() == "")
                {
                    sErr = sErr + "行" + (i + 1) + "调出仓库不能为空\n";
                    continue;
                }
                if (gridView1.GetRowCellValue(i, gridCol调入仓库) == null || gridView1.GetRowCellValue(i, gridCol调入仓库).ToString().Trim() == "")
                {
                    sErr = sErr + "行" + (i + 1) + "调入仓库不能为空\n";
                    continue;
                }
                if (gridView1.GetRowCellValue(i, gridCol调出部门) == null || gridView1.GetRowCellValue(i, gridCol调出部门).ToString().Trim() == "")
                {
                    sErr = sErr + "行" + (i + 1) + "调出部门不能为空\n";
                    continue;
                }
                if (gridView1.GetRowCellValue(i, gridCol调入部门) == null || gridView1.GetRowCellValue(i, gridCol调入部门).ToString().Trim() == "")
                {
                    sErr = sErr + "行" + (i + 1) + "调入部门不能为空\n";
                    continue;
                }
                if (gridView1.GetRowCellValue(i, gridCol出库类别) == null || gridView1.GetRowCellValue(i, gridCol出库类别).ToString().Trim() == "")
                {
                    sErr = sErr + "行" + (i + 1) + "出库类别不能为空\n";
                    continue;
                }
                if (gridView1.GetRowCellValue(i, gridCol入库类别) == null || gridView1.GetRowCellValue(i, gridCol入库类别).ToString().Trim() == "")
                {
                    sErr = sErr + "行" + (i + 1) + "入库类别不能为空\n";
                    continue;
                }
                if (FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol本次调拨)) == 0)
                {
                    sErr = sErr + "行" + (i + 1) + "调拨数量必须大于0\n";
                    continue;
                }

                string s调出仓库 = gridView1.GetRowCellValue(i, gridCol调出仓库).ToString().Trim();
                string s调入仓库 = gridView1.GetRowCellValue(i, gridCol调入仓库).ToString().Trim();
                string s调出部门 = gridView1.GetRowCellValue(i, gridCol调出部门).ToString().Trim();
                string s调入部门 = gridView1.GetRowCellValue(i, gridCol调入部门).ToString().Trim();
                string s出库类别 = gridView1.GetRowCellValue(i, gridCol出库类别).ToString().Trim();
                string s入库类别 = gridView1.GetRowCellValue(i, gridCol入库类别).ToString().Trim();
                if (s调出仓库 == s调入仓库)
                {
                    sErr = sErr + "行" + (i + 1) + "调拨仓库不能相同\n";
                    continue;
                }
                if (s调出部门 == s调入部门)
                {
                    sErr = sErr + "行" + (i + 1) + "调拨部门不能相同\n";
                    continue;
                }

                iCou += 1;
            }
            if (sErr.Trim().Length > 0)
            {
                throw new Exception(sErr);
            }
            if (iCou == 0)
            {
                throw new Exception("没有符合调拨条件的行");
            }

            aList = new System.Collections.ArrayList();

            sSQL = "select * from @u8.TransVouch where 1=-1";
            DataTable dtTransVouch = clsSQLCommond.ExecQuery(sSQL);

            sSQL = "select * from @u8.TransVouchs  where 1=-1";
            DataTable dtTransVouchs = clsSQLCommond.ExecQuery(sSQL);

            DateTime dtm1        = dtm单据日期1.DateTime;
            long     iTrID       = 0;
            long     iTrIDDetail = 0;

            GetID("tr", out iTrID, out iTrIDDetail);
            sSQL = "select max(cast(isnull(cNumber,0) as decimal(18,9))) as Maxnumber From @u8.VoucherHistory  with (NOLOCK) Where  CardNumber='0304'  and (cSeed = '" + dtm1.ToString("yyMM") + "' or cSeed = '" + dtm1.ToString("yyyyMM") + "')";
            DataTable dtCode  = clsSQLCommond.ExecQuery(sSQL);
            long      iTrCode = Convert.ToInt64(dtCode.Rows[0]["Maxnumber"]);

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                if (!Convert.ToBoolean(gridView1.GetRowCellValue(i, gridColiChk)))
                {
                    continue;
                }

                //if (ReturnObjectToInt(gridView1.GetRowCellValue(i, gridColbUsed)) != 0)
                //    continue;

                string  s调出仓库    = gridView1.GetRowCellValue(i, gridCol调出仓库).ToString().Trim();
                string  s调入仓库    = gridView1.GetRowCellValue(i, gridCol调入仓库).ToString().Trim();
                string  s调出部门    = gridView1.GetRowCellValue(i, gridCol调出部门).ToString().Trim();
                string  s调入部门    = gridView1.GetRowCellValue(i, gridCol调入部门).ToString().Trim();
                string  s出库类别    = gridView1.GetRowCellValue(i, gridCol出库类别).ToString().Trim();
                string  s入库类别    = gridView1.GetRowCellValue(i, gridCol入库类别).ToString().Trim();
                string  s生产订单号   = gridView1.GetRowCellValue(i, gridCol生产订单号).ToString().Trim();
                decimal d本次调拨    = FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol本次调拨));
                string  sTrCode1 = "";

                bool b相同表头 = false;
                long lID   = 0;

                #region 表头

                for (int j = 0; j < dtTransVouch.Rows.Count; j++)
                {
                    string s调出仓库2  = dtTransVouch.Rows[j]["cOWhCode"].ToString().Trim();
                    string s调入仓库2  = dtTransVouch.Rows[j]["cIWhCode"].ToString().Trim();
                    string s调出部门2  = dtTransVouch.Rows[j]["cODepCode"].ToString().Trim();
                    string s调入部门2  = dtTransVouch.Rows[j]["cIDepCode"].ToString().Trim();
                    string s出库类别2  = dtTransVouch.Rows[j]["cORdCode"].ToString().Trim();
                    string s入库类别2  = dtTransVouch.Rows[j]["cIRdCode"].ToString().Trim();
                    string s生产订单号2 = dtTransVouch.Rows[j]["cMPoCode"].ToString().Trim();

                    if (s调出仓库 == s调出仓库2 && s调入仓库 == s调入仓库2 && s调出部门 == s调出部门2 && s调入部门 == s调入部门2 &&
                        s出库类别 == s出库类别2 && s入库类别 == s入库类别2)
                    {
                        lID      = Convert.ToInt64(dtTransVouch.Rows[j]["ID"]);
                        sTrCode1 = dtTransVouch.Rows[j]["cTVCode"].ToString().Trim();
                        b相同表头    = true;
                        break;
                    }
                }
                if (!b相同表头)
                {
                    iTrID += 1;
                    lID    = iTrID;

                    DataRow drTransVouch = dtTransVouch.NewRow();
                    iTrCode += 1;
                    sTrCode1 = sSetTransVouchCode(iTrCode);
                    s调拨单号    = s调拨单号 + "\n" + sTrCode1;

                    iTrID += 1;
                    lID    = iTrID;
                    drTransVouch["cTVCode"]       = sTrCode1;
                    drTransVouch["dTVDate"]       = FrameBaseFunction.ClsBaseDataInfo.sLogDate;
                    drTransVouch["cOWhCode"]      = s调出仓库;
                    drTransVouch["cIWhCode"]      = s调入仓库;
                    drTransVouch["cODepCode"]     = s调出部门;
                    drTransVouch["cIDepCode"]     = s调入部门;
                    drTransVouch["cPersonCode"]   = DBNull.Value;
                    drTransVouch["cIRdCode"]      = s入库类别;
                    drTransVouch["cORdCode"]      = s出库类别;
                    drTransVouch["cTVMemo"]       = DBNull.Value;
                    drTransVouch["cDefine1"]      = DBNull.Value;
                    drTransVouch["cDefine2"]      = DBNull.Value;
                    drTransVouch["cDefine3"]      = DBNull.Value;
                    drTransVouch["cDefine4"]      = DBNull.Value;
                    drTransVouch["cDefine5"]      = DBNull.Value;
                    drTransVouch["cDefine6"]      = DBNull.Value;
                    drTransVouch["cDefine7"]      = DBNull.Value;
                    drTransVouch["cDefine8"]      = DBNull.Value;
                    drTransVouch["cDefine9"]      = DBNull.Value;
                    drTransVouch["cDefine10"]     = DBNull.Value;
                    drTransVouch["cAccounter"]    = DBNull.Value;
                    drTransVouch["cMaker"]        = FrameBaseFunction.ClsBaseDataInfo.sUserName;
                    drTransVouch["iNetLock"]      = 0;
                    drTransVouch["ID"]            = lID;
                    drTransVouch["VT_ID"]         = 89;
                    drTransVouch["cVerifyPerson"] = DBNull.Value;
                    drTransVouch["dVerifyDate"]   = DBNull.Value;
                    drTransVouch["cPSPCode"]      = gridView1.GetRowCellValue(i, gridCol物料编码);
                    drTransVouch["cMPoCode"]      = s生产订单号;
                    drTransVouch["iQuantity"]     = FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol生产订单数量));
                    drTransVouch["bTransFlag"]    = DBNull.Value;
                    drTransVouch["cDefine11"]     = DBNull.Value;
                    drTransVouch["cDefine12"]     = DBNull.Value;
                    drTransVouch["cDefine13"]     = DBNull.Value;
                    drTransVouch["cDefine14"]     = DBNull.Value;
                    drTransVouch["cDefine15"]     = DBNull.Value;
                    drTransVouch["cDefine16"]     = DBNull.Value;
                    //drTransVouch["ufts"] = DBNull.Value;
                    drTransVouch["iproorderid"]      = DBNull.Value;
                    drTransVouch["cOrderType"]       = "生产订单";
                    drTransVouch["cTranRequestCode"] = DBNull.Value;
                    drTransVouch["cVersion"]         = DBNull.Value;
                    drTransVouch["BomId"]            = DBNull.Value;
                    drTransVouch["cFree1"]           = DBNull.Value;
                    drTransVouch["cFree2"]           = DBNull.Value;
                    drTransVouch["cFree3"]           = DBNull.Value;
                    drTransVouch["cFree4"]           = DBNull.Value;
                    drTransVouch["cFree5"]           = DBNull.Value;
                    drTransVouch["cFree6"]           = DBNull.Value;
                    drTransVouch["cFree7"]           = DBNull.Value;
                    drTransVouch["cFree8"]           = DBNull.Value;
                    drTransVouch["cFree9"]           = DBNull.Value;
                    drTransVouch["cFree10"]          = DBNull.Value;
                    drTransVouch["cAppTVCode"]       = DBNull.Value;
                    drTransVouch["csource"]          = 1;
                    drTransVouch["itransflag"]       = "正向";
                    //drTransVouch["cModifyPerson"] = FrameBaseFunction.ClsBaseDataInfo.sUserName;
                    //drTransVouch["dModifyDate"] = FrameBaseFunction.ClsBaseDataInfo.sLogDate;
                    drTransVouch["dnmaketime"] = Get当前服务器时间();
                    //drTransVouch["dnmodifytime"] = FrameBaseFunction.ClsBaseDataInfo.sLogDate;
                    drTransVouch["dnverifytime"]   = DBNull.Value;
                    drTransVouch["ireturncount"]   = 0;
                    drTransVouch["iverifystate"]   = 0;
                    drTransVouch["iswfcontrolled"] = 0;

                    dtTransVouch.Rows.Add(drTransVouch);

                    aList.Add(clsGetSQL.GetInsertSQL(FrameBaseFunction.ClsBaseDataInfo.sUFDataBaseName, "TransVouch", dtTransVouch, dtTransVouch.Rows.Count - 1));
                }
                #endregion

                if (FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol本次调拨)) == 0)
                {
                    throw new Exception("行" + (i + 1) + "调拨仓库不能相同");
                }

                DataRow drTransVouchs = dtTransVouchs.NewRow();
                drTransVouchs["cTVCode"]     = sTrCode1;
                drTransVouchs["cInvCode"]    = gridView1.GetRowCellValue(i, gridCol子件编码);
                drTransVouchs["RdsID"]       = DBNull.Value;
                drTransVouchs["iTVQuantity"] = FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol本次调拨));

                if (FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol子件换算率)) != 0)
                {
                    drTransVouchs["iinvexchrate"] = FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol子件换算率));
                    drTransVouchs["iTVNum"]       = FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol本次调拨)) / FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol子件换算率)));
                    drTransVouchs["cAssUnit"]     = gridView1.GetRowCellValue(i, gridCol子件辅助计量);
                }

                drTransVouchs["iTVACost"]  = DBNull.Value;
                drTransVouchs["iTVAPrice"] = DBNull.Value;
                drTransVouchs["iTVPCost"]  = DBNull.Value;
                drTransVouchs["iTVPPrice"] = DBNull.Value;
                drTransVouchs["cTVBatch"]  = DBNull.Value;
                drTransVouchs["dDisDate"]  = DBNull.Value;
                drTransVouchs["cFree1"]    = DBNull.Value;
                drTransVouchs["cFree2"]    = DBNull.Value;
                drTransVouchs["cDefine22"] = DBNull.Value;
                drTransVouchs["cDefine23"] = DBNull.Value;
                drTransVouchs["cDefine24"] = DBNull.Value;
                drTransVouchs["cDefine25"] = DBNull.Value;
                drTransVouchs["cDefine26"] = DBNull.Value;
                drTransVouchs["cDefine27"] = DBNull.Value;
                if (gridView1.GetRowCellValue(i, gridCol项目编码).ToString().Trim() != "")
                {
                    drTransVouchs["cItemCode"]   = gridView1.GetRowCellValue(i, gridCol项目编码);
                    drTransVouchs["cItem_class"] = "00";
                }
                drTransVouchs["fSaleCost"]  = 0;
                drTransVouchs["fSalePrice"] = 0;
                drTransVouchs["cName"]      = DBNull.Value;
                drTransVouchs["cItemCName"] = DBNull.Value;

                iTrIDDetail                  += 1;
                drTransVouchs["autoID"]       = iTrIDDetail;
                drTransVouchs["ID"]           = lID;
                drTransVouchs["iMassDate"]    = DBNull.Value;
                drTransVouchs["cBarCode"]     = DBNull.Value;
                drTransVouchs["cFree3"]       = DBNull.Value;
                drTransVouchs["cFree4"]       = DBNull.Value;
                drTransVouchs["cFree5"]       = DBNull.Value;
                drTransVouchs["cFree6"]       = DBNull.Value;
                drTransVouchs["cFree7"]       = DBNull.Value;
                drTransVouchs["cFree8"]       = DBNull.Value;
                drTransVouchs["cFree9"]       = DBNull.Value;
                drTransVouchs["cFree10"]      = DBNull.Value;
                drTransVouchs["cDefine28"]    = DBNull.Value;
                drTransVouchs["cDefine29"]    = DBNull.Value;
                drTransVouchs["cDefine30"]    = DBNull.Value;
                drTransVouchs["cDefine31"]    = DBNull.Value;
                drTransVouchs["cDefine32"]    = DBNull.Value;
                drTransVouchs["cDefine33"]    = DBNull.Value;
                drTransVouchs["cDefine34"]    = DBNull.Value;
                drTransVouchs["cDefine35"]    = DBNull.Value;
                drTransVouchs["cDefine36"]    = DBNull.Value;
                drTransVouchs["cDefine37"]    = DBNull.Value;
                drTransVouchs["iMPoIds"]      = DBNull.Value;
                drTransVouchs["cBVencode"]    = DBNull.Value;
                drTransVouchs["cInVouchCode"] = DBNull.Value;
                drTransVouchs["dMadeDate"]    = DBNull.Value;
                drTransVouchs["cMassUnit"]    = DBNull.Value;
                drTransVouchs["iTRIds"]       = DBNull.Value;
                drTransVouchs["AppTransIDS"]  = DBNull.Value;
                drTransVouchs["iSSoType"]     = 0;
                drTransVouchs["iSSodid"]      = DBNull.Value;
                drTransVouchs["iDSoType"]     = 0;
                drTransVouchs["iDSodid"]      = DBNull.Value;
                drTransVouchs["bCosting"]     = 1;
                drTransVouchs["cvmivencode"]  = DBNull.Value;
                drTransVouchs["cinposcode"]   = DBNull.Value;
                drTransVouchs["coutposcode"]  = DBNull.Value;
                drTransVouchs["iinvsncount"]  = DBNull.Value;
                drTransVouchs["comcode"]      = DBNull.Value;
                drTransVouchs["cmocode"]      = gridView1.GetRowCellDisplayText(i, gridCol生产订单号);
                drTransVouchs["imoseq"]       = gridView1.GetRowCellDisplayText(i, gridCol生产订单行号);
                drTransVouchs["invcode"]      = gridView1.GetRowCellValue(i, gridCol物料编码);
                drTransVouchs["iomids"]       = DBNull.Value;
                drTransVouchs["imoids"]       = gridView1.GetRowCellDisplayText(i, gridCol生产订单子件ID);
                //drTransVouchs["corufts"] = DBNull.Value;
                drTransVouchs["iExpiratDateCalcu"] = 0;
                drTransVouchs["cExpirationdate"]   = DBNull.Value;
                drTransVouchs["dExpirationdate"]   = DBNull.Value;
                drTransVouchs["cBatchProperty1"]   = DBNull.Value;
                drTransVouchs["cBatchProperty2"]   = DBNull.Value;
                drTransVouchs["cBatchProperty3"]   = DBNull.Value;
                drTransVouchs["cBatchProperty4"]   = DBNull.Value;
                drTransVouchs["cBatchProperty5"]   = DBNull.Value;
                drTransVouchs["cBatchProperty6"]   = DBNull.Value;
                drTransVouchs["cBatchProperty7"]   = DBNull.Value;
                drTransVouchs["cBatchProperty8"]   = DBNull.Value;
                drTransVouchs["cBatchProperty9"]   = DBNull.Value;
                drTransVouchs["cBatchProperty10"]  = DBNull.Value;
                drTransVouchs["cciqbookcode"]      = DBNull.Value;

                dtTransVouchs.Rows.Add(drTransVouchs);

                //gridView1.SetRowCellValue(i, gridColbUsed, 1);

                aList.Add(clsGetSQL.GetInsertSQL(FrameBaseFunction.ClsBaseDataInfo.sUFDataBaseName, "TransVouchs", dtTransVouchs, dtTransVouchs.Rows.Count - 1));


                sSQL = "update @u8.mom_moallocate set TransQty = isnull(TransQty,0)  + " + FrameBaseFunction.ClsBaseDataInfo.ReturnDecimal(gridView1.GetRowCellValue(i, gridCol本次调拨)) + " where AllocateId = " + gridView1.GetRowCellDisplayText(i, gridCol生产订单子件ID);
                aList.Add(sSQL);
            }
            //更改调拨单据号
            sSQL = "select isnull(max(cNumber),0) as Maxnumber From @u8.VoucherHistory  with (NOLOCK) Where  CardNumber='0304'  and (cSeed = '" + dtm1.ToString("yyMM") + "' or cSeed = '" + dtm1.ToString("yyyyMM") + "')";
            DataTable dtCodeTemp = clsSQLCommond.ExecQuery(sSQL);
            if (dtCodeTemp.Rows[0]["Maxnumber"].ToString().Trim() == "0")
            {
                sSQL = "insert into @u8.VoucherHistory(cardnumber,ccontent,ccontentrule,cseed,cnumber,bempty)values('0304','日期','月','" + dtm1.ToString("yyMM") + "','1',0)";
                aList.Add(sSQL);
            }
            else
            {
                sSQL = "update @u8.VoucherHistory set cNumber = '" + iTrCode.ToString().Trim() + "' Where CardNumber='0304' and (cSeed='" + dtm1.ToString("yyyyMM") + "' or cSeed='" + dtm1.ToString("yyMM") + "')";
                aList.Add(sSQL);
            }

            if (iTrID >= 1000000000)
            {
                iTrID = iTrID - 1000000000;
            }
            if (iTrIDDetail >= 1000000000)
            {
                iTrIDDetail = iTrIDDetail - 1000000000;
            }

            sSQL = "update UFSystem..UA_Identity set iFatherID = " + iTrID + ",iChildID=" + iTrIDDetail + "  where cAcc_Id = '200' and cVouchType = 'tr'";
            aList.Add(sSQL);

            if (aList.Count > 0 && dtTransVouch != null && dtTransVouch.Rows.Count > 0 && dtTransVouchs != null && dtTransVouchs.Rows.Count > 0)
            {
                clsSQLCommond.ExecSqlTran(aList);
                MsgBox("生单成功", s调拨单号);
                GetGrid();
            }
        }
Example #32
0
        /// <summary> scans a Grib file to gather information that could be used to
        /// create an index or dump the metadata contents.
        ///
        /// </summary>
        /// <param name="getProducts">products have enough information for data extractions
        /// </param>
        /// <param name="oneRecord">returns after processing one record in the Grib file
        /// </param>
        /// <throws>  NotSupportedException </throws>
        public void scan(bool getProducts, bool oneRecord)
        {
            long start = (DateTime.Now.Ticks - 621355968000000000) / 10000;

            // stores the number of times a particular GDS is used
            //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
            System.Collections.Hashtable  gdsCounter = new System.Collections.Hashtable();
            Grib1ProductDefinitionSection pds        = null;
            Grib1GridDefinitionSection    gds        = null;
            long startOffset = -1;


            while (InputStream.Position < InputStream.Length)
            {
                if (seekHeader(InputStream, InputStream.Length, out startOffset))
                {
                    // Read Section 0 Indicator Section
                    Grib1IndicatorSection is_Renamed = new Grib1IndicatorSection(InputStream);

                    // EOR (EndOfRecord) calculated so skipping data sections is faster
                    long EOR = InputStream.Position + is_Renamed.GribLength - is_Renamed.Length;

                    // Read Section 1 Product Definition Section PDS
                    pds = new Grib1ProductDefinitionSection(InputStream);
                    if (pds.LengthErr)
                    {
                        continue;
                    }

                    if (pds.gdsExists())
                    {
                        // Read Section 2 Grid Definition Section GDS
                        gds = new Grib1GridDefinitionSection(InputStream);
                    }
                    else
                    {
                        // GDS doesn't exist so make one



                        gds = (Grib1GridDefinitionSection) new Grib1Grid(pds);
                    }

                    // obtain BMS or BDS offset in the file for this product
                    long dataOffset = 0;
                    if (pds.Center == 98)
                    {
                        // check for ecmwf offset by 1 bug
                        int length = (int)GribNumbers.uint3(InputStream);                          // should be length of BMS
                        if ((length + InputStream.Position) < EOR)
                        {
                            dataOffset = InputStream.Position - 3;                             // ok
                        }
                        else
                        {
                            dataOffset = InputStream.Position - 2;
                        }
                    }
                    else
                    {
                        dataOffset = InputStream.Position;
                    }

                    // position filePointer to EndOfRecord
                    InputStream.Seek(EOR, System.IO.SeekOrigin.Begin);


                    // assume scan ok
                    if (getProducts)
                    {
                        Grib1Product gp = new Grib1Product(header, pds, getGDSkey(gds, gdsCounter), dataOffset, InputStream.Position);
                        products.Add(gp);
                    }
                    else
                    {
                        Grib1Record gr = new Grib1Record(header, is_Renamed, pds, gds, dataOffset, InputStream.Position, startOffset);
                        records.Add(gr);
                    }

                    if (oneRecord)
                    {
                        return;
                    }

                    // early return because ending "7777" missing
                    if (InputStream.Position > InputStream.Length)
                    {
                        InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        Console.Error.WriteLine("Grib1Input: possible file corruption");
                        checkGDSkeys(gds, gdsCounter);
                        return;
                    }
                }         // end if seekHeader
            }             // end while raf.Position < raf.Length


            //   (System.currentTimeMillis()- start) + " milliseconds");
            checkGDSkeys(gds, gdsCounter);
            return;
        }         // end scan
Example #33
0
        object[] Deserialize(byte[] data)
        {
            if (data.Length < 1 || data[0] == 0)
            {
                return(new object[0]);
            }

            var r = new ObjectList();

            var len   = data.Length;
            var count = data[0];

            var p = 1;

            while (p < len && r.Count < count)
            {
                switch ((char)data[p])
                {
                case 'N':
                    r.Add((object)null);
                    p += 1;
                    break;

                case 'B':
                    r.Add((object)(data [p + 1] != 0));
                    p += 2;
                    break;

                case 'b':
                    r.Add((object)data[p + 1]);
                    p += 2;
                    break;

                case 'I':
                    r.Add((object)BitConverter.ToInt32(data, p + 1));
                    p += 5;
                    break;

                case 'D': {
                    double d = 0.0;
                                                #if MF_FRAMEWORK_VERSION_V4_3
                    d = ReadDouble(data, p + 1);
                                                #else
                    d = BitConverter.ToDouble(data, p + 1);
                                                #endif
                    r.Add((object)d);
                    p += 9;
                }
                break;

                case 'F': {
                    float f = 0.0f;
                                                #if MF_FRAMEWORK_VERSION_V4_3
                    f = ReadSingle(data, p + 1);
                                                #else
                    f = BitConverter.ToSingle(data, p + 1);
                                                #endif
                    r.Add((object)f);
                    p += 5;
                }
                break;

                case 'S':
                {
                    var slen = data[p + 1];
                    r.Add((object)new string (Encoding.UTF8.GetChars(data, p + 2, slen)));
                    p += 2 + slen;
                }
                break;

                default:
                    throw new NotSupportedException("Cannot read type: " + (char)data[p]);
                }
            }

                        #if MF_FRAMEWORK_VERSION_V4_3
            return((object[])r.ToArray(typeof(object)));
                        #else
            return(r.ToArray());
                        #endif
        }
Example #34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ptEnd1"></param>
        /// <param name="endPt1Heading"></param>
        /// <param name="ptEnd2"></param>
        /// <param name="endPt2Heading"></param>
        /// <param name="padLeft"></param>
        /// <param name="padRight"></param>
        /// <param name="padTop"></param>
        /// <param name="padBottom"></param>
        /// <returns></returns>
        public static PointF[] CalcOrthogonalPoints(PointF ptEnd1, CompassHeading endPt1Heading, PointF ptEnd2, CompassHeading endPt2Heading, float padLeft, float padRight, float padTop, float padBottom)
        {
            System.Collections.ArrayList ptsOut = new System.Collections.ArrayList();

            System.Drawing.Size frontHeadingVector = Geometry.CompassHeadingToVector(endPt1Heading);
            System.Drawing.Size backHeadingVector  = Geometry.CompassHeadingToVector(endPt2Heading);

            // Maximum of 6 points from a 25x25 grid
            int[] row   = new int[] { 2, -1, -1, -1, -1, 2 };
            int[] col   = new int[] { 2, -1, -1, -1, -1, 2 };
            int   front = 0;
            int   back  = 5;

            // Determine the row and column in the grid
            // for each endpoint
            if (ptEnd1.X < ptEnd2.X)
            {
                col[front] = 1;
                col[back]  = 3;
            }
            else if (ptEnd1.X > ptEnd2.X)
            {
                col[front] = 3;
                col[back]  = 1;
            }
            else
            {
                col[front] = col[front] + (1 * frontHeadingVector.Width);
                col[back]  = col[back] + (1 * backHeadingVector.Width);
            }

            if (ptEnd1.Y < ptEnd2.Y)
            {
                row[front] = 1;
                row[back]  = 3;
            }
            else if (ptEnd1.Y > ptEnd2.Y)
            {
                row[front] = 3;
                row[back]  = 1;
            }
            else
            {
                row[front] = row[front] + (1 * frontHeadingVector.Height);
                row[back]  = row[back] + (1 * backHeadingVector.Height);
            }

            row[front + 1] = row[front] + (1 * frontHeadingVector.Height);
            col[front + 1] = col[front] + (1 * frontHeadingVector.Width);
            front++;

            row[back - 1] = row[back] + (1 * backHeadingVector.Height);
            col[back - 1] = col[back] + (1 * backHeadingVector.Width);
            back--;

            bool hasMoved     = true;
            bool isOrthogonal = (row[front] == row[back]) || (col[front] == col[back]);

            while (!isOrthogonal && front <= back)
            {
                // Determine if vectors will intersect
                PointF ptFront0         = new PointF(col[front], row[front]);
                PointF ptFront1         = new PointF(col[front] + (10 * frontHeadingVector.Width), row[front] + (10 * frontHeadingVector.Height));
                PointF ptBack0          = new PointF(col[back], row[back]);
                PointF ptBack1          = new PointF(col[back] + (10 * backHeadingVector.Width), row[back] + (10 * backHeadingVector.Height));
                bool   vectorsIntersect = Geometry.LinesIntersect(ptFront0, ptFront1, ptBack0, ptBack1);

                // Determine if vectors are pointed towards each other
                SizeF szShift         = frontHeadingVector + backHeadingVector;
                bool  vectorsOpposite = (szShift.Width == 0 && szShift.Height == 0);
                bool  vectorsSame     = (frontHeadingVector == backHeadingVector);

                if (!hasMoved || (!vectorsIntersect && !vectorsSame))
                {
                    if (vectorsOpposite || vectorsSame)
                    {
                        int turnDirection = 1;                          // 1 == counterclockwise, -1 = clockwise

                        // Change direction so that vectors are at right angles

                        if (frontHeadingVector.Width > 0)
                        {
                            // Pointing right
                            if (row[front] < row[back])
                            {
                                turnDirection = 1;
                            }
                            else
                            {
                                turnDirection = -1;
                            }
                        }
                        else if (frontHeadingVector.Width < 0)
                        {
                            // Pointing left
                            if (row[front] < row[back])
                            {
                                turnDirection = -1;
                            }
                            else
                            {
                                turnDirection = 1;
                            }
                        }
                        else if (frontHeadingVector.Height > 0)
                        {
                            // Pointing down
                            if (col[front] < col[back])
                            {
                                turnDirection = 1;
                            }
                            else
                            {
                                turnDirection = -1;
                            }
                        }
                        else if (frontHeadingVector.Height < 0)
                        {
                            // Pointing up
                            if (col[front] < col[back])
                            {
                                turnDirection = -1;
                            }
                            else
                            {
                                turnDirection = 1;
                            }
                        }

                        System.Drawing.Size szTmp = frontHeadingVector;
                        frontHeadingVector.Width  = (szTmp.Height * turnDirection);
                        frontHeadingVector.Height = (szTmp.Width * turnDirection);
                    }
                    else
                    {
                        frontHeadingVector = backHeadingVector;
                    }

                    // Go to next front point
                    row[front + 1] = row[front];
                    col[front + 1] = col[front];
                    front++;
                }

                hasMoved = false;

                // Calculate next front grid point and test to see if
                // the line segments are orthogonal yet.
                int rowFront = row[front] + (1 * frontHeadingVector.Height);
                rowFront = (rowFront < 4) ? (rowFront) : (4);
                rowFront = (rowFront > 0) ? (rowFront) : (0);
                if (rowFront != row[front])
                {
                    hasMoved   = true;
                    row[front] = rowFront;
                }

                int colFront = col[front] + (1 * frontHeadingVector.Width);
                colFront = (colFront < 4) ? (colFront) : (4);
                colFront = (colFront > 0) ? (colFront) : (0);
                if (colFront != col[front])
                {
                    hasMoved   = true;
                    col[front] = colFront;
                }

                isOrthogonal = (row[front] == row[back]) || (col[front] == col[back]);
            }

            int numEmptySlots = back - front - 1;

            numEmptySlots = (numEmptySlots > 0) ? (numEmptySlots) : (0);
            int numPoints = 6 - numEmptySlots;

            // First point is always endpoint 1
            ptsOut.Add(ptEnd1);

            // Compress array and elimate unused points

            while ((front < back) && (back < 6))
            {
                if (row[front] == -1 || col[front] == -1)
                {
                    row[front] = row[back];
                    col[front] = col[back];
                    row[back]  = -1;
                    col[back]  = -1;
                    back++;
                }
                front++;
            }

            // Look at the other four points and see if they should
            // be added.
            for (int addIdx = 1; addIdx < numPoints - 1; addIdx++)
            {
                if ((row[addIdx - 1] != row[addIdx + 1]) && (col[addIdx - 1] != col[addIdx + 1]))
                {
                    PointF ptAdd = Geometry.GetOrthogonalPoint(ptEnd1, ptEnd2, row[addIdx], col[addIdx], padLeft, padRight, padTop, padBottom);

                    bool found = false;
                    for (int ptIdx = 0; !found && ptIdx < ptsOut.Count; ptIdx++)
                    {
                        found = (ptAdd == (PointF)ptsOut[ptIdx]);
                    }

                    if (!found)
                    {
                        ptsOut.Add(ptAdd);
                    }
                }
            }

            // Last point is always endpoint 2
            ptsOut.Add(ptEnd2);

            return((PointF[])ptsOut.ToArray(typeof(PointF)));
        }
Example #35
0
        /// <summary>
        /// 获取盘点药品
        /// </summary>
        /// <param name="p_dtbMedicine"></param>
        /// <returns></returns>
        internal long m_dtbGetMedicine(out DataTable p_dtbMedicine)
        {
            long lngRes = 0;

            p_dtbMedicine = null;

            Control ctlCurrent = null;//当前正在查询的控件

            if (m_objViewer.m_rdbCheckSortNum.Checked)
            {
                if (string.IsNullOrEmpty(m_objViewer.m_txtCheckSortNum1.Text) || string.IsNullOrEmpty(m_objViewer.m_txtCheckSortNum2.Text))
                {
                    MessageBox.Show("请先输入完整查询条件", "药品盘点", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    m_objViewer.m_txtCheckSortNum1.Focus();
                    return(-1);
                }
                ctlCurrent = m_objViewer.m_txtCheckSortNum1;
                lngRes     = m_objDomain.m_lngGetMedicineBySortNum(m_objViewer.m_txtCheckSortNum1.Text, m_objViewer.m_txtCheckSortNum2.Text, m_objViewer.m_strStorageID, out p_dtbMedicine);
            }
            else if (m_objViewer.m_rdbMedicineCode.Checked)
            {
                if (string.IsNullOrEmpty(m_objViewer.m_txtMedicineCode1.Text) || string.IsNullOrEmpty(m_objViewer.m_txtMedicineCode2.Text))
                {
                    MessageBox.Show("请先输入完整查询条件", "药品盘点", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    m_objViewer.m_txtMedicineCode1.Focus();
                    return(-1);
                }
                ctlCurrent = m_objViewer.m_txtMedicineCode1;
                lngRes     = m_objDomain.m_lngGetMedicineByMedicineCode(m_objViewer.m_txtMedicineCode1.Text, m_objViewer.m_txtMedicineCode2.Text, m_objViewer.m_strStorageID, out p_dtbMedicine);
            }
            else if (m_objViewer.m_rdbMedicinePreptype.Checked)
            {
                if (m_objViewer.m_cboMediciePreptype.SelectedIndex == -1 || m_objViewer.m_cboMediciePreptype.SelectedItem == null)
                {
                    MessageBox.Show("请先选择药品剂型", "药品盘点", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    m_objViewer.m_cboMediciePreptype.Focus();
                    return(-1);
                }

                ctlCurrent = m_objViewer.m_cboMediciePreptype;
                com.digitalwave.iCare.ValueObject.clsMEDICINEPREPTYPE_VO objTypeVO = m_objViewer.m_cboMediciePreptype.SelectedItem as com.digitalwave.iCare.ValueObject.clsMEDICINEPREPTYPE_VO;
                lngRes = m_objDomain.m_lngGetMedicineByMedicinePreptype(objTypeVO.m_strMEDICINEPREPTYPE_CHR, m_objViewer.m_strStorageID, out p_dtbMedicine);
            }
            else if (m_objViewer.m_rdbRackNum.Checked)
            {
                if (string.IsNullOrEmpty(m_objViewer.m_txtRackNum1.Text) || string.IsNullOrEmpty(m_objViewer.m_txtRackNum2.Text))
                {
                    MessageBox.Show("请先输入完整查询条件", "药品盘点", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    m_objViewer.m_txtRackNum1.Focus();
                    return(-1);
                }
                ctlCurrent = m_objViewer.m_txtRackNum1;
                lngRes     = m_objDomain.m_lngGetMedicineByMedicineRackNO(m_objViewer.m_txtRackNum1.Text, m_objViewer.m_txtRackNum2.Text, m_objViewer.m_strStorageID, out p_dtbMedicine);
            }
            else if (m_objViewer.m_rdbSetType.Checked)
            {
                System.Collections.ArrayList arr = new System.Collections.ArrayList();
                if (m_objViewer.lsvMedType.CheckedItems.Count > 0)
                {
                    for (int i1 = 0; i1 < m_objViewer.lsvMedType.CheckedItems.Count; i1++)
                    {
                        arr.Add(this.m_objViewer.lsvMedType.CheckedItems[i1].Tag.ToString());
                    }
                    lngRes = m_objDomain.m_lngGetMedicineByMedicineType(arr, m_objViewer.m_strStorageID, out p_dtbMedicine);
                }
                else
                {
                    MessageBox.Show("至少选择一种药品类型", "药品盘点", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    m_objViewer.lsvMedType.Focus();
                    return(-1);
                }
            }
            else if (m_objViewer.m_rdbAll.Checked)
            {
                lngRes = m_objDomain.m_lngGetAllMedicine(m_objViewer.m_strStorageID, out p_dtbMedicine);
            }
            else
            {
                MessageBox.Show("请先选择筛选条件", "药品盘点", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(-1);
            }

            if (p_dtbMedicine == null || p_dtbMedicine.Rows.Count == 0)
            {
                DialogResult drResult = MessageBox.Show("未找到符合条件的药品信息,是否更改筛选条件继续查找?", "药品盘点", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (drResult == DialogResult.Yes)
                {
                    if (ctlCurrent != null)
                    {
                        ctlCurrent.Focus();
                    }
                    return(-1);
                }
                else
                {
                    return(0);
                }
            }
            return(1);
        }
        public ActionResult GetGridJSON(Models.question.W00015 actRow)
        {
            ZhWebClassV3.UserData userData = ZhWebClassV3.UserHelper.GetUserData();
            JObject jo = new JObject();

            try
            {
                #region ACall_checkIsDBNull
                actRow.qId       = ZhConfig.ZhIniObj.ACall_checkIsDBNull(actRow.qId);
                actRow.RowStatus = ZhConfig.ZhIniObj.ACall_checkIsDBNull(actRow.RowStatus);
                actRow.seq       = ZhConfig.ZhIniObj.ACall_checkIsDBNull(actRow.seq);
                #endregion

                #region 取得問卷的題目
                strSql.Clear();
                strSql.Append("select * from Q30_questionMaster where qId='" + actRow.qId.ToString() + "' ");
                DataTable tbl_QueryData1 = ZhClass.SqlTool.GetDataTable(ZhConfig.GlobalSystemVar.StrConnection1, strSql.ToString(), "tbl_QueryData1");

                //2018/05/14 edit By Ray
                strSql.Clear();
                strSql.Append("select top 1 * from Q30_questionDetail where qId='" + actRow.qId.ToString() + "' ");
                DataTable tbl_QueryData2 = ZhClass.SqlTool.GetDataTable(ZhConfig.GlobalSystemVar.StrConnection1, strSql.ToString(), "tbl_QueryData2");

                JArray jaQd = new JArray();

                for (int i = 0; i < tbl_QueryData2.Rows.Count; i++)
                {
                    strSql.Clear();
                    strSql.Append("select * from Q30_questionDD where qId='" + actRow.qId.ToString() + "' and seq='" + tbl_QueryData2.Rows[i]["seq"].ToString() + "'");
                    DataTable tbl_QueryData3 = ZhClass.SqlTool.GetDataTable(ZhConfig.GlobalSystemVar.StrConnection1, strSql.ToString(), "tbl_QueryData2");

                    JArray jaQdd = new JArray();
                    if (tbl_QueryData2.Rows[i]["topicType"].ToString() != "tx" && tbl_QueryData2.Rows[i]["topicType"].ToString() != "mt" && tbl_QueryData2.Rows[i]["topicType"].ToString() != "li")
                    {
                        for (int j = 0; j < tbl_QueryData3.Rows.Count; j++)
                        {
                            JObject joQdd = new JObject();
                            joQdd.Add("optionId", tbl_QueryData3.Rows[j]["optionId"].ToString());
                            joQdd.Add("optionName", tbl_QueryData3.Rows[j]["optionName"].ToString());
                            jaQdd.Add(joQdd);
                        }
                    }

                    JObject joQd = new JObject();
                    joQd.Add("seq", tbl_QueryData2.Rows[i]["seq"].ToString());
                    joQd.Add("qNbr", tbl_QueryData2.Rows[i]["qNbr"].ToString());
                    joQd.Add("topic", tbl_QueryData2.Rows[i]["topic"].ToString());
                    joQd.Add("topicType", tbl_QueryData2.Rows[i]["topicType"].ToString());
                    joQd.Add("required", tbl_QueryData2.Rows[i]["required"].ToString());
                    joQd.Add("memo", tbl_QueryData2.Rows[i]["memo"].ToString());
                    joQd.Add("mTitle", tbl_QueryData2.Rows[i]["memo1"].ToString());
                    joQd.Add("options", tbl_QueryData2.Rows[i]["options"].ToString());
                    joQd.Add("joQdds", jaQdd);
                    jaQd.Add(joQd);
                }
                #endregion

                JArray jaAn = new JArray();

                if (actRow.RowStatus.ToString() == "M")
                {
                    strSql.Clear();
                    strSql.Append("select answerId, answer, topicType from Q30_answer where qId='" + actRow.qId + "' and seq='" + actRow.seq + "' ");
                    DataTable tbl_answer = ZhClass.SqlTool.GetDataTable(ZhConfig.GlobalSystemVar.StrConnection1, strSql.ToString(), "tbl_answer");
                    if (tbl_answer.Rows.Count > 0)
                    {
                        for (int i = 0; i < tbl_answer.Rows.Count; i++)
                        {
                            JObject joAn = new JObject();
                            joAn.Add("answerId", tbl_answer.Rows[i]["answerId"].ToString());
                            joAn.Add("answer", tbl_answer.Rows[i]["answer"].ToString());
                            joAn.Add("topicType", tbl_answer.Rows[i]["topicType"].ToString());
                            jaAn.Add(joAn);
                        }
                    }
                }

                #region 取得該題圖片說明
                string  savePath   = "~/Upload_Jpg/" + actRow.qId + "/" + tbl_QueryData2.Rows[0]["seq"].ToString();
                JArray  jaa        = new JArray();
                JObject itemObject = new JObject();
                int     count      = 0;
                string  img        = "";
                if (Directory.Exists(Server.MapPath(savePath))) //如果該題有圖片資料夾
                {
                    string[] files = System.IO.Directory.GetFiles(Server.MapPath(savePath), "*.*", System.IO.SearchOption.AllDirectories);
                    System.Collections.ArrayList dirlist = new System.Collections.ArrayList();/*用來儲存只有目錄名的集合*/
                    foreach (string item in files)
                    {
                        dirlist.Add(Path.GetFileNameWithoutExtension(item));//走訪每個元素只取得目錄名稱(不含路徑)並加入dirlist集合中
                        string fileName     = dirlist[count] + files[count].Substring(files[count].Length - 4, 4);
                        string imagePath    = Path.Combine(Server.MapPath(savePath), fileName);
                        byte[] imageBytes   = System.IO.File.ReadAllBytes(imagePath);
                        string base64string = Convert.ToBase64String(imageBytes);
                        img += "<div id=\"" + fileName.Substring(0, fileName.Length - 4) + "\" class='imgDiv'><a href='#' onclick=\"btnPhotoView('" + fileName + "')\"><img style='width:400px' class='imgcontent' id=\"" + fileName.Substring(0, fileName.Length - 4) + "src\" src=\"data:image/jpg;base64, " + base64string + "\" ></a><br/>" + fileName + "</div>";
                        count++;
                    }
                }
                itemObject.Add("img", img);
                jaa.Add(itemObject);
                jo.Add("dirImg", jaa); //圖片
                #endregion

                jo.Add("title", tbl_QueryData1.Rows[0]["title"].ToString());
                jo.Add("description", tbl_QueryData1.Rows[0]["description"].ToString());
                jo.Add("qNum", tbl_QueryData1.Rows[0]["qNum"].ToString());
                jo.Add("joQds", jaQd);
                jo.Add("joAns", jaAn);

                return(Content(JsonConvert.SerializeObject(jo), "application/json"));
            }
            catch (Exception ex)
            {
                jo = new JObject();
                jo.Add("status", "error");
                jo.Add("error", ex.Message);
                return(Content(JsonConvert.SerializeObject(jo), "application/json"));
            }
        }
Example #37
0
        static public string MakeHtml(yaf.pages.ForumPage basePage, string bbcode, bool DoFormatting)
        {
            System.Collections.ArrayList codes = new System.Collections.ArrayList();
            const string codeFormat            = ".code@{0}.";

            Match m      = r_code2.Match(bbcode);
            int   nCodes = 0;

            while (m.Success)
            {
                string before_replace = m.Groups[0].Value;
                string after_replace  = m.Groups["inner"].Value;

                try
                {
                    HighLighter hl = new HighLighter();
                    hl.ReplaceEnter = true;
                    after_replace   = hl.colorText(after_replace, System.Web.HttpContext.Current.Server.MapPath(Data.ForumRoot + "defs/"), m.Groups["language"].Value);
                }
                catch (Exception x)
                {
                    if (basePage.IsAdmin)
                    {
                        basePage.AddLoadMessage(x.Message);
                    }
                    after_replace = FixCode(after_replace);
                }

                bbcode = bbcode.Replace(before_replace, string.Format(codeFormat, nCodes++));
                codes.Add(string.Format("<div class='code'><b>Code:</b><div class='innercode'>{0}</div></div>", after_replace));
                m = r_code2.Match(bbcode);
            }

            m = r_code1.Match(bbcode);
            while (m.Success)
            {
                string before_replace = m.Groups[0].Value;
                string after_replace  = FixCode(m.Groups["inner"].Value);
                bbcode = bbcode.Replace(before_replace, string.Format(codeFormat, nCodes++));
                codes.Add(string.Format("<div class='code'><b>Code:</b><div class='innercode'>{0}</div></div>", after_replace));
                m = r_code1.Match(bbcode);
            }

            m = r_size.Match(bbcode);

            while (m.Success)
            {
                ///Console.WriteLine("{0}",m.Groups["size"]);
                int    i = GetNumber(m.Groups["size"].Value);
                string tmp;
                if (i < 1)
                {
                    tmp = m.Groups["inner"].Value;
                }
                else if (i > 9)
                {
                    tmp = string.Format("<span style=\"font-size:{1}\">{0}</span>", m.Groups["inner"].Value, GetFontSize(9));
                }
                else
                {
                    tmp = string.Format("<span style=\"font-size:{1}\">{0}</span>", m.Groups["inner"].Value, GetFontSize(i));
                }
                bbcode = bbcode.Substring(0, m.Groups[0].Index) + tmp + bbcode.Substring(m.Groups[0].Index + m.Groups[0].Length);
                m      = r_size.Match(bbcode);
            }

            bbcode = FormatMsg.iAddSmiles(basePage, bbcode);

            if (DoFormatting)
            {
                NestedReplace(ref bbcode, r_bold, "<b>${inner}</b>");
                NestedReplace(ref bbcode, r_strike, "<s>${inner}</s>");
                NestedReplace(ref bbcode, r_italic, "<i>${inner}</i>");
                NestedReplace(ref bbcode, r_underline, "<u>${inner}</u>");
                // e-mails
                NestedReplace(ref bbcode, r_email2, "<a href=\"mailto:${email}\">${inner}</a>", new string[] { "email" });
                NestedReplace(ref bbcode, r_email1, "<a href=\"mailto:${inner}\">${inner}</a>");
                // urls
                if (basePage.BoardSettings.BlankLinks)
                {
                    NestedReplace(ref bbcode, r_url2, "<a target=\"_blank\" href=\"${http}${url}\">${inner}</a>", new string[] { "url", "http" }, new string[] { "", "http://" });
                    NestedReplace(ref bbcode, r_url1, "<a target=\"_blank\" href=\"${http}${inner}\">${http}${inner}</a>", new string[] { "http" }, new string[] { "http://" });
                }
                else
                {
                    NestedReplace(ref bbcode, r_url2, "<a href=\"${http}${url}\">${inner}</a>", new string[] { "url", "http" }, new string[] { "", "http://" });
                    NestedReplace(ref bbcode, r_url1, "<a href=\"${http}${inner}\">${http}${inner}</a>", new string[] { "http" }, new string[] { "http://" });
                }
                // font
                NestedReplace(ref bbcode, r_font, "<span style=\"font-family:${font}\">${inner}</span>", new string[] { "font" });
                NestedReplace(ref bbcode, r_color, "<span style=\"color:${color}\">${inner}</span>", new string[] { "color" });
                // bullets
                bbcode = r_bullet.Replace(bbcode, "<li>");
                NestedReplace(ref bbcode, r_list4, "<ol type=\"i\">${inner}</ol>");
                NestedReplace(ref bbcode, r_list3, "<ol type=\"a\">${inner}</ol>");
                NestedReplace(ref bbcode, r_list2, "<ol>${inner}</ol>");
                NestedReplace(ref bbcode, r_list2, "<ul>${inner}</ul>");
                // alignment
                NestedReplace(ref bbcode, r_center, "<div align=\"center\">${inner}</div>");
                NestedReplace(ref bbcode, r_left, "<div align=\"left\">${inner}</div>");
                NestedReplace(ref bbcode, r_right, "<div align=\"right\">${inner}</div>");
                // image
                NestedReplace(ref bbcode, r_img, "<img src=\"${inner}\"/>");

                bbcode = r_hr.Replace(bbcode, "<hr noshade/>");
                bbcode = r_br.Replace(bbcode, "<br/>");
            }

            while (r_quote2.IsMatch(bbcode))
            {
                bbcode = r_quote2.Replace(bbcode, "<div class='quote'><b>${quote} wrote:</b><div class='innerquote'>${inner}</div></div>");
            }
            while (r_quote1.IsMatch(bbcode))
            {
                bbcode = r_quote1.Replace(bbcode, "<div class='quote'><b>Quote:</b><div class='innerquote'>${inner}</div></div>");
            }

            m = r_post.Match(bbcode);
            while (m.Success)
            {
                string link = Forum.GetLink(Pages.posts, "m={0}#{0}", m.Groups["post"]);
                if (basePage.BoardSettings.BlankLinks)
                {
                    bbcode = bbcode.Replace(m.Groups[0].ToString(), string.Format("<a target=\"_blank\" href=\"{0}\">{1}</a>", link, m.Groups["inner"]));
                }
                else
                {
                    bbcode = bbcode.Replace(m.Groups[0].ToString(), string.Format("<a href=\"{0}\">{1}</a>", link, m.Groups["inner"]));
                }
                m = r_post.Match(bbcode);
            }

            m = r_topic.Match(bbcode);
            while (m.Success)
            {
                string link = Forum.GetLink(Pages.posts, "t={0}", m.Groups["topic"]);
                if (basePage.BoardSettings.BlankLinks)
                {
                    bbcode = bbcode.Replace(m.Groups[0].ToString(), string.Format("<a target=\"_blank\" href=\"{0}\">{1}</a>", link, m.Groups["inner"]));
                }
                else
                {
                    bbcode = bbcode.Replace(m.Groups[0].ToString(), string.Format("<a href=\"{0}\">{1}</a>", link, m.Groups["inner"]));
                }
                m = r_topic.Match(bbcode);
            }

            while (nCodes > 0)
            {
                bbcode = bbcode.Replace(string.Format(codeFormat, --nCodes), codes[nCodes].ToString());
            }

            return(bbcode);
        }
Example #38
0
        /// <summary>
        /// 保存
        /// </summary>
        private void btnSave()
        {
            try
            {
                gridView1.FocusedRowHandle -= 1;
                gridView1.FocusedRowHandle += 1;
            }
            catch { }
            sSQL = "select * from _LookUpType where 1=-1";
            DataTable dt = clsSQLCommond.ExecQuery(sSQL);

            string sErr = "";

            aList = new System.Collections.ArrayList();
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                if (gridView1.GetRowCellDisplayText(i, gridColiID).ToString().Trim() == "")
                {
                    continue;
                }
                if (gridView1.GetRowCellValue(i, gridColiType).ToString().Trim() == "")
                {
                    sErr = sErr + "行" + (i + 1) + "类型不能为空\n";
                    continue;
                }

                if (gridView1.GetRowCellDisplayText(i, gridColtstamp).ToString().Trim() == "")
                {
                    DataRow dr = dt.NewRow();
                    dr["iID"]    = gridView1.GetRowCellValue(i, gridColiID).ToString().Trim();
                    dr["iType"]  = gridView1.GetRowCellValue(i, gridColiType).ToString().Trim();
                    dr["Remark"] = gridView1.GetRowCellValue(i, gridColRemark).ToString().Trim();
                    dt.Rows.Add(dr);
                    sSQL = clsGetSQL.GetInsertSQL("_LookUpType", dt, dt.Rows.Count - 1);
                    aList.Add(sSQL);
                }
                if (gridView1.GetRowCellDisplayText(i, gridColiSave).ToString().Trim() == "edit")
                {
                    DataRow dr = dt.NewRow();
                    dr["iID"]    = gridView1.GetRowCellValue(i, gridColiID).ToString().Trim();
                    dr["iType"]  = gridView1.GetRowCellValue(i, gridColiType).ToString().Trim();
                    dr["Remark"] = gridView1.GetRowCellValue(i, gridColRemark).ToString().Trim();
                    dt.Rows.Add(dr);
                    sSQL = clsGetSQL.GetUpdateSQL("_LookUpType", dt, dt.Rows.Count - 1);
                    aList.Add(sSQL);
                }
            }

            if (sErr.Trim().Length > 0)
            {
                MsgBox("提示", sErr);
                return;
            }

            if (aList.Count > 0)
            {
                int iCou = clsSQLCommond.ExecSqlTran(aList);
                MessageBox.Show("保存成功!\n合计执行语句:" + iCou + "条");
                GetGrid();
            }
        }
Example #39
0
        protected void InsertImaginaryIndentDedentTokens()
        {
            IToken t = stream.LT(1);

            stream.Consume();
            IList hiddenTokens;

            // if not a NEWLINE, doesn't signal indent/dedent work; just enqueue
            if (t.Type != PythonLexer.NEWLINE)
            {
                hiddenTokens = stream.GetTokens(lastTokenAddedIndex + 1, t.TokenIndex - 1);
                if (hiddenTokens != null)
                {
                    tokens.AddRange(hiddenTokens);
                }
                lastTokenAddedIndex = t.TokenIndex;
                tokens.Add(t);
                return;
            }

            // save NEWLINE in the queue
            //System.out.println("found newline: "+t+" stack is "+StackString());
            hiddenTokens = stream.GetTokens(lastTokenAddedIndex + 1, t.TokenIndex - 1);
            if (hiddenTokens != null)
            {
                tokens.AddRange(hiddenTokens);
            }
            lastTokenAddedIndex = t.TokenIndex;
            tokens.Add(t);

            // grab first token of next line
            t = stream.LT(1);
            stream.Consume();

            hiddenTokens = stream.GetTokens(lastTokenAddedIndex + 1, t.TokenIndex - 1);
            if (hiddenTokens != null)
            {
                tokens.AddRange(hiddenTokens);
            }
            lastTokenAddedIndex = t.TokenIndex;

            // compute cpos as the char pos of next non-WS token in line
            int cpos = t.CharPositionInLine;             // column dictates indent/dedent

            if (t.Type == Token.EOF)
            {
                cpos = -1;                 // pretend EOF always happens at left edge
            }
            else if (t.Type == PythonLexer.LEADING_WS)
            {
                cpos = t.Text.Length;
            }

            //System.out.println("next token is: "+t);

            // compare to last indent level
            int lastIndent = Peek();

            //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent);
            if (cpos > lastIndent)
            {             // they indented; track and gen INDENT
                Push(cpos);
                //System.out.println("Push("+cpos+"): "+StackString());
                IToken indent = new ClassicToken(PythonParser.INDENT, "");
                indent.CharPositionInLine = t.CharPositionInLine;
                indent.Line = t.Line;
                tokens.Add(indent);
            }
            else if (cpos < lastIndent)
            {             // they dedented
                // how far back did we dedent?
                int prevIndex = FindPreviousIndent(cpos);
                //System.out.println("dedented; prevIndex of cpos="+cpos+" is "+prevIndex);
                // generate DEDENTs for each indent level we backed up over
                for (int d = sp - 1; d >= prevIndex; d--)
                {
                    IToken dedent = new ClassicToken(PythonParser.DEDENT, "");
                    dedent.CharPositionInLine = t.CharPositionInLine;
                    dedent.Line = t.Line;
                    tokens.Add(dedent);
                }
                sp = prevIndex;                 // pop those off indent level
            }
            if (t.Type != PythonLexer.LEADING_WS)
            {             // discard WS
                tokens.Add(t);
            }
        }
Example #40
0
        private void Common_AppEventOccured(Common.AppEventTypeEnum eventType, Object[] parms)
        {
            switch (eventType)
            {
            case Common.AppEventTypeEnum.AppStarted:
                DeleteTemporaryFiles();
                ButtonLoadDataEnabled(false);
                ButtonOpenLoadedFileFolderEnabled(false);
                ButtonEncryptEnabled(false);
                ButtonDecryptEnabled(false);
                LabelKeySizeUpdate();
                break;

            case Common.AppEventTypeEnum.AlgoPrepared:
                this.PanelButtonsEnabled(true);
                ButtonLoadDataEnabled(true);
                ButtonOpenLoadedFileFolderEnabled(false);
                ButtonEncryptEnabled(false);
                ButtonDecryptEnabled(false);
                this.PrintRSAParameters(false);
                break;

            case Common.AppEventTypeEnum.FileLoaded:
                ButtonEncryptEnabled(true);
                ButtonOpenLoadedFileFolderEnabled(true);
                ButtonDecryptEnabled(false);
                this.fileLoaded = true;
                RichTextBoxConsoleAddText("File to encrypt loaded!");
                break;

            case Common.AppEventTypeEnum.EncryptionDone:
                RichTextBoxConsoleAddText(String.Format("Generating final output! : {0}", DateTime.Now));
                PostProcessEncryptedFiles();
                RichTextBoxConsoleAddText(String.Format("Encryption done! Verify encrypted.enc file! : {0}", DateTime.Now));
                this.PanelButtonsEnabled(true);
                ButtonDecryptEnabled(true);
                UpdateCurrOperationStatus("");
                break;

            case Common.AppEventTypeEnum.AlgoPreparationStarted:
                this.PanelButtonsEnabled(false);
                LabelKeySizeUpdate();
                break;

            case Common.AppEventTypeEnum.AlgoPreparationRestarted:
                this.ParamsToDefault();
                this.DeleteTemporaryFiles();
                ButtonLoadDataEnabled(false);
                ButtonOpenLoadedFileFolderEnabled(false);
                ButtonEncryptEnabled(false);
                ButtonDecryptEnabled(false);
                RichTextBoxConsoleClear();
                break;

            case Common.AppEventTypeEnum.EncryptionStarted:
                UpdateCurrOperationStatus("Encryption in progress...");
                this.PanelButtonsEnabled(false);
                workersFinishedJob = 0;
                break;

            case Common.AppEventTypeEnum.DecryptionStarted:
                UpdateCurrOperationStatus("Decryption in progress...");
                this.PanelButtonsEnabled(false);
                workersFinishedJob = 0;
                pBSteps            = new System.Collections.ArrayList();
                break;

            case Common.AppEventTypeEnum.DecryptionDone:
                RichTextBoxConsoleAddText(String.Format("Generating final output! : {0}", DateTime.Now));
                PostProcessDecryptedFiles();
                this.PanelButtonsEnabled(true);
                RichTextBoxConsoleAddText(String.Format("Decryption done! Verify decrypted.dec file! : {0}", DateTime.Now));
                UpdateCurrOperationStatus("");
                break;

            case Common.AppEventTypeEnum.SettingsSaved:
                if (parms == null)
                {
                    break;
                }
                if ((UInt32)parms[0] != Properties.AppSettings.Default.keySize)
                {
                    Common_AppEventOccured(Common.AppEventTypeEnum.AlgoPreparationRestarted, null);
                    RichTextBoxConsoleAddText(String.Format("Key size modified. Key size: {0} bits", Properties.AppSettings.Default.keySize));
                }
                if ((Int32)parms[1] != Properties.AppSettings.Default.showKeyInBase &&
                    (lastOperation == Common.AppEventTypeEnum.AlgoPrepared || lastOperation == Common.AppEventTypeEnum.SettingsSaved))
                {
                    RichTextBoxConsoleClear();
                    PrintRSAParameters(false);
                }
                LabelKeySizeUpdate();
                break;

            case Common.AppEventTypeEnum.NrThreadsBiggerThanNrCores:
                RichTextBoxConsoleAddText("Warning! Running more threads than cores on the machine!");
                break;

            case Common.AppEventTypeEnum.WorkerFinishedJob:
                if (parms != null && parms[0] != null && parms[1] != null)
                {
                    if ((Common.AppEventTypeEnum)parms[1] != Common.AppEventTypeEnum.EncryptionDone && parms[2] != null)
                    {
                        pBSteps.Add(parms[2]);
                    }
                    workersFinishedJob++;
                    if (workersFinishedJob == Properties.AppSettings.Default.threadsRSA)
                    {
                        Common.RaiseAppEvent((Common.AppEventTypeEnum)parms[1], null);
                    }
                }
                break;

            case Common.AppEventTypeEnum.OperationAborted:
                PanelButtonsEnabled(true);
                // This will ensure that the timer and progressBar are updated and stopped
                SetProgressBarToMax();
                UpdateCurrOperationStatus("");
                RichTextBoxConsoleAddText("Operation aborted!");
                break;

            case Common.AppEventTypeEnum.RSADataExported:

                String messageToShow = String.Empty;

                switch (Properties.AppSettings.Default.impExpKeySetting)
                {
                case (Int32)Common.ImpExpKeyDataTypeEnum.BothKeys:
                    messageToShow = String.Format("RSA data exported to: {0}", Properties.AppSettings.Default.encryptionKeysExportFileName);;
                    break;

                case (Int32)Common.ImpExpKeyDataTypeEnum.PrivateKey:
                    messageToShow = String.Format("Private key exported to: {0}", Properties.AppSettings.Default.privateKeyExportFileName);
                    break;

                case (Int32)Common.ImpExpKeyDataTypeEnum.PublicKey:
                    messageToShow = String.Format("Public key exported to: {0}", Properties.AppSettings.Default.publicKeyExportFileName);
                    break;

                default:
                    break;
                }

                MessageWindow.ShowInfo(messageToShow);
                break;

            case Common.AppEventTypeEnum.RSADataImported:
                switch (rSACE.ActionsAvailable)
                {
                case RSACustomEncryption.ActionsAvailableEnum.Encrypt | RSACustomEncryption.ActionsAvailableEnum.Decrypt:
                case RSACustomEncryption.ActionsAvailableEnum.Encrypt:
                    this.PanelButtonsEnabled(true);
                    ButtonLoadDataEnabled(true);
                    ButtonOpenLoadedFileFolderEnabled(false);
                    ButtonEncryptEnabled(false);
                    ButtonDecryptEnabled(true);
                    this.PrintRSAParameters(true);
                    break;

                case RSACustomEncryption.ActionsAvailableEnum.Decrypt:
                    PanelButtonsEnabled(true);
                    ButtonLoadDataEnabled(false);
                    ButtonOpenLoadedFileFolderEnabled(false);
                    ButtonEncryptEnabled(false);
                    ButtonDecryptEnabled(true);
                    break;
                }
                break;

            case Common.AppEventTypeEnum.DecryptionImpossible:
                if (parms != null)
                {
                    workersFinishedJob++;
                    if (workersFinishedJob == Properties.AppSettings.Default.threadsRSA)
                    {
                        MessageWindow.ShowError("Cannot decrypt data with the provided key!");
                        SetProgressBarToMax();
                        UpdateCurrOperationStatus("");
                        this.PanelButtonsEnabled(true);
                    }
                }
                break;

            default: break;
            }

            lastOperation = eventType;
        }
Example #41
0
        private void MapSubclasses(System.Collections.ArrayList subclasses, System.Collections.Specialized.StringCollection extendedClassesNames, System.Collections.ArrayList mappedClassesNames, System.Xml.XmlTextWriter writer)
        {
            System.Collections.ArrayList mappedSubclassesNames = new System.Collections.ArrayList();
            // Map each subclass after the class it extends
            while (subclasses.Count > 0)
            {
                for (int i = subclasses.Count - 1; i >= 0; i--)
                {
                    System.Type type = subclasses[i] as System.Type;
                    string      extendedClassName = extendedClassesNames[i];
                    if (extendedClassName == null)
                    {
                        throw new MappingException("You must specify the Extends attribute of the Subclass: " + type.FullName);
                    }

                    if (!mappedClassesNames.Contains(extendedClassName) &&
                        !mappedSubclassesNames.Contains(extendedClassName))
                    {
                        bool extendedClassFoundButNotMappedYet = false;
                        // Make sure that the extended class is mapped (in this assembly)
                        foreach (System.Type subclass in subclasses)
                        {
                            if (HbmWriterHelper.GetNameWithAssembly(subclass)
                                == extendedClassName)
                            {
                                if (subclass == type)
                                {
                                    throw new MappingException("The Subclass " + type.FullName + " extends itself.");
                                }
                                else
                                {
                                    extendedClassFoundButNotMappedYet = true;
                                    break;
                                }
                            }
                        }
                        if (extendedClassFoundButNotMappedYet)
                        {
                            continue;                             // Map this one later
                        }
                        // Else unknown extended class:
                        //   Assume it is mapped somewhere else and map this subclass
                    }

                    if (IsSubclass(type, typeof(SubclassAttribute)))
                    {
                        HbmWriter.WriteSubclass(writer, type);
                    }
                    else if (IsSubclass(type, typeof(JoinedSubclassAttribute)))
                    {
                        HbmWriter.WriteJoinedSubclass(writer, type);
                    }
                    else if (IsSubclass(type, typeof(UnionSubclassAttribute)))
                    {
                        HbmWriter.WriteUnionSubclass(writer, type);
                    }

                    // Note: Do not add to mappedClassesNames because it is for x-subclasses (and a x-subclasses shouldn't extend another x-subclasses)
                    mappedSubclassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type));
                    subclasses.RemoveAt(i);
                    extendedClassesNames.RemoveAt(i);
                }
            }
        }
Example #42
0
        /// <summary>
        /// 分析一个字符串,根据开始字符串和结束字符串进行分割,并返回分割生成的字符串数组
        /// 这些字符串数组的偶数号元素为开始字符串和结束字符串间的部分
        /// 例如分析字符串"aaa[bbb]ccc"产生字符串数组"aaa","bbb","ccc"
        /// </summary>
        /// <param name="strText">供分析的字符串</param>
        /// <param name="strHead">开始字符串</param>
        /// <param name="strEnd">结束字符串</param>
        /// <returns>生成的字符串数组</returns>
        private static string[] AnalyseVariableString(
            string strText,
            string strHead,
            string strEnd)
        {
            // 若原始字符串无效或者没有任何可用的参数则退出函数
            if (strText == null ||
                strHead == null ||
                strEnd == null ||
                strHead.Length == 0 ||
                strEnd.Length == 0 ||
                strText.Length == 0)
            {
                return new string[] { strText }
            }
            ;

            int index = strText.IndexOf(strHead);

            // 若原始字符串没有变量标记则退出函数
            if (index < 0)
            {
                return new string[] { strText }
            }
            ;

            System.Collections.ArrayList myList = new System.Collections.ArrayList();
            string strKey;
            int    index2;
            int    LastIndex = 0;

            do
            {
                // 查找有 "[内容]" 样式的子字符串
                // 若没有找到 "[" 和 "]"的字符对则退出循环
                index2 = strText.IndexOf(strEnd, index + 1);

                if (index2 > index)
                {
                    // 若 "[" 符号后面出现 "]"符号则存在 "[]"字符对
                    // 修正查找结果以保证 "[]"字符对中不出现字符 "["
                    int index3 = index;
                    do
                    {
                        index  = index3;
                        index3 = strText.IndexOf(strHead, index3 + 1);
                    }while(index3 > index && index3 < index2);

                    // 获得字符对夹着的子字符串,该子字符串为参数名
                    // 若该参数名有效则向输出结果输出参数值
                    // 否则不进行额外的处理
                    strKey = strText.Substring(index + strHead.Length, index2 - index - strHead.Length);
                    if (LastIndex < index)
                    {
                        myList.Add(strText.Substring(LastIndex, index - LastIndex));
                    }
                    else
                    {
                        myList.Add("");
                    }
                    myList.Add(strKey);
                    index     = index2 + strEnd.Length;
                    LastIndex = index;
                }
                else
                {
                    break;
                }
            }while(index >= 0 && index < strText.Length);
            // 添加处理过后剩余的字符串
            if (LastIndex < strText.Length)
            {
                myList.Add(strText.Substring(LastIndex));
            }
            return((string[])myList.ToArray(typeof(string)));
        } //private static string[] AnalyseVariableString
    }     //public class VariableString
}
Example #43
0
        /// <summary> Writes the mapping of all mapped classes of the specified assembly in the specified stream. </summary>
        /// <param name="stream">Where the xml is written.</param>
        /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param>
        public virtual void Serialize(System.IO.Stream stream, System.Reflection.Assembly assembly)
        {
            if (stream == null)
            {
                throw new System.ArgumentNullException("stream");
            }
            if (assembly == null)
            {
                throw new System.ArgumentNullException("assembly");
            }

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();
            if (WriteDateComment)
            {
                writer.WriteComment(string.Format("Generated from NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u")));
            }
            WriteHibernateMapping(writer, null);

            // Write imports (classes decorated with the [ImportAttribute])
            foreach (System.Type type in assembly.GetTypes())
            {
                object[] imports = type.GetCustomAttributes(typeof(ImportAttribute), false);
                foreach (ImportAttribute import in imports)
                {
                    writer.WriteStartElement("import");
                    if (import.Class != null && import.Class != string.Empty)
                    {
                        writer.WriteAttributeString("class", import.Class);
                    }
                    else                     // Assume that it is the current type that must be imported
                    {
                        writer.WriteAttributeString("class", HbmWriterHelper.GetNameWithAssembly(type));
                    }
                    if (import.Rename != null && import.Rename != string.Empty)
                    {
                        writer.WriteAttributeString("rename", import.Rename);
                    }
                    writer.WriteEndElement();
                }
            }

            // Write classes and x-subclasses (classes must come first if inherited by "external" subclasses)
            int classCount = 0;

            System.Collections.ArrayList mappedClassesNames = new System.Collections.ArrayList();
            foreach (System.Type type in assembly.GetTypes())
            {
                if (!IsClass(type))
                {
                    continue;
                }
                HbmWriter.WriteClass(writer, type);
                mappedClassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type));
                classCount++;
            }

            System.Collections.ArrayList subclasses = new System.Collections.ArrayList();
            System.Collections.Specialized.StringCollection extendedClassesNames = new System.Collections.Specialized.StringCollection();
            foreach (System.Type type in assembly.GetTypes())
            {
                if (!IsSubclass(type))
                {
                    continue;
                }
                bool        map = true;
                System.Type t   = type;
                while ((t = t.DeclaringType) != null)
                {
                    if (IsClass(t) || AreSameSubclass(type, t)) // If a base class is also mapped... (Note: A x-subclass can only contain x-subclasses of the same family)
                    {
                        map = false;                            // This class's mapping is already included in the mapping of the base class
                        break;
                    }
                }
                if (map)
                {
                    subclasses.Add(type);
                    if (IsSubclass(type, typeof(SubclassAttribute)))
                    {
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(SubclassAttribute), false)[0] as SubclassAttribute).Extends);
                    }
                    else if (IsSubclass(type, typeof(JoinedSubclassAttribute)))
                    {
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(JoinedSubclassAttribute), false)[0] as JoinedSubclassAttribute).Extends);
                    }
                    else if (IsSubclass(type, typeof(UnionSubclassAttribute)))
                    {
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(UnionSubclassAttribute), false)[0] as UnionSubclassAttribute).Extends);
                    }
                }
            }
            classCount += subclasses.Count;
            MapSubclasses(subclasses, extendedClassesNames, mappedClassesNames, writer);

            writer.WriteEndElement();             // </hibernate-mapping>
            writer.WriteEndDocument();
            writer.Flush();

            if (classCount == 0)
            {
                throw new MappingException("The following assembly contains no mapped classes: " + assembly.FullName);
            }
            if (!Validate)
            {
                return;
            }

            // Validate the generated XML stream
            try
            {
                writer.BaseStream.Position = 0;
                System.Xml.XmlTextReader       tr = new System.Xml.XmlTextReader(writer.BaseStream);
                System.Xml.XmlValidatingReader vr = new System.Xml.XmlValidatingReader(tr);

                // Open the Schema
                System.IO.Stream schema = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Mapping.Attributes.nhibernate-mapping.xsd");
                vr.Schemas.Add("urn:nhibernate-mapping-2.2", new System.Xml.XmlTextReader(schema));
                vr.ValidationType          = System.Xml.ValidationType.Schema;
                vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlValidationHandler);

                _stop = false;
                while (vr.Read() && !_stop)                // Read to validate (stop at the first error)
                {
                    ;
                }
            }
            catch (System.Exception ex)
            {
                Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine);
            }
        }
Example #44
0
        ///-----------------------------------------------------------------
        /// <summary>
        /// 对    象:BtnSCISend
        /// 事    件:Click
        /// 功    能:发送数据:选择字符串发送时,以字符串的形式发送出去,
        ///          选择十进制发送时,以十进制的形式发送
        ///          选择十六进制发送时,以十六进制的形式发送出
        /// 函数调用:SCISendData:通过串口发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///-----------------------------------------------------------------
        private void BtnSCISend_Click(object sender, EventArgs e)
        {
            this.TSSLState.Text = "过程提示: 执行发送数据...";

            bool Flag;         //判断数据发送是否成功
            int  i, count = 0; //len保存发送数据的长度
            int  len;

            //0表示选择是字符发送,1表示的是十进制发送,2表示十六进制发送
            int SendType;

            SendType = CbSCISendType.SelectedIndex;

            //定义一个ArrayList类的实例对象,实现一个数组,其大小在添加元
            //素时自动变化
            System.Collections.ArrayList SendData = new
                                                    System.Collections.ArrayList();

            //如果串口没有打开
            if (!sci.IsOpen)
            {
                //状态条进行提示
                this.TSSLState.Text += "请先打开串口!";
                return;
            }
            //如果发送数据为空
            if (this.TbSCISend.Text == string.Empty)
            {
                this.TSSLState.Text += "发送数据不得为空!";
                return;
            }

            if (SendType == 0)//选择的是以字符串方式发送
            {
                this.TSSLState.Text = "以字符串方式发送数据!";
                //将要发送的数据进行编码,并获取编码后的数据长度
                len = System.Text.Encoding.Default.GetBytes(this.TbSCISend.Text).Length;
                //sci.SCIReceInt(SCIPort,len);//设置产生接收中断的字节数  【2014-5-5 注释,否则会导致程序无响应】
                //动态分配len字节单元内容用来存放发送数据
                PublicVar.g_SendByteArray = new byte[len];
                //获取TbSCISend文本的码值
                PublicVar.g_SendByteArray =
                    System.Text.Encoding.Default.GetBytes(this.TbSCISend.Text);
            }
            else //选择的是以十进制或者是十六进制发送数据
            {
                //sci.SCIReceInt(SCIPort, 1);//设置产生接收中断的字节数    【2014-5-5 注释,否则会导致程序无响应】
                foreach (string str in this.TbSCISend.Text.Split(','))
                {
                    //排除掉连续两个逗号,说明之间没有数
                    if (str != string.Empty)
                    {
                        if (SendType == 1)//选择的是以十进制方式发送
                        {
                            //将文本框中的数转化为十进制存入ArrayList类的实例对象
                            SendData.Add(Convert.ToByte(str, 10));
                            count++;//进行计数,统计有效的数据个数
                        }
                        else
                        {
                            //将文本框中的数转化为十六进制存入ArrayList类的实例对象
                            SendData.Add(Convert.ToByte(str, 16));
                            count++;//进行计数,统计有效的数据个数
                        }
                    }
                }
                //动态分配空间存放发送数据
                PublicVar.g_SendByteArray = new byte[count];

                //将已经转化后的数据放入到全局变量g_SendByteArray中
                for (i = 0; i < count; i++)
                {
                    PublicVar.g_SendByteArray[i] = (byte)SendData[i];
                }
            }

            //发送全局变量_SendByteArray中的数据,并返回结果
            Flag = sci.SCISendData(ref PublicVar.g_SendByteArray);

            if (Flag == true)//数据发送成功
            {
                this.TSSLState.Text += "数据发送成功!";
            }
            else
            {
                this.TSSLState.Text += "数据发送失败!";
            }
        }
Example #45
0
        private void ParseGroupByFieldList(string FieldList)
        {
            /*
             * Parses FieldList into FieldInfo objects and adds them to the GroupByFieldInfo private member
             *
             * FieldList syntax: fieldname[ alias]|operatorname(fieldname)[ alias],...
             *
             * Supported Operators: count,sum,max,min,first,last
             */
            if (GroupByFieldList == FieldList)
            {
                return;
            }
            GroupByFieldInfo = new System.Collections.ArrayList();
            FieldInfo Field; string[] FieldParts; string[] Fields = FieldList.Split(',');

            for (int i = 0; i <= Fields.Length - 1; i++)
            {
                Field = new FieldInfo();
                //Parse FieldAlias
                FieldParts = Fields[i].Trim().Split(' ');
                switch (FieldParts.Length)
                {
                case 1:
                    //to be set at the end of the loop
                    break;

                case 2:
                    Field.FieldAlias = FieldParts[1];
                    break;

                default:
                    throw new ArgumentException("Too many spaces in field definition: '" + Fields[i] + "'.");
                }
                //Parse FieldName and Aggregate
                FieldParts = FieldParts[0].Split('(');
                switch (FieldParts.Length)
                {
                case 1:
                    Field.FieldName = FieldParts[0];
                    break;

                case 2:
                    Field.Aggregate = FieldParts[0].Trim().ToLower();        //we're doing a case-sensitive comparison later
                    Field.FieldName = FieldParts[1].Trim(' ', ')');
                    break;

                default:
                    throw new ArgumentException("Invalid field definition: '" + Fields[i] + "'.");
                }
                if (Field.FieldAlias == null)
                {
                    if (Field.Aggregate == null)
                    {
                        Field.FieldAlias = Field.FieldName;
                    }
                    else
                    {
                        Field.FieldAlias = Field.Aggregate + "of" + Field.FieldName;
                    }
                }
                GroupByFieldInfo.Add(Field);
            }
            GroupByFieldList = FieldList;
        }
Example #46
0
        static byte[] Serialize(object[] arguments)
        {
            if (arguments == null || arguments.Length == 0)
            {
                return(new byte[0]);
            }

            var parts = new ByteList();

            parts.Add((byte)arguments.Length);
            foreach (var a in arguments)
            {
                if (a == null)
                {
                    parts.Add((byte)'N');
                }
                else if (a is int)
                {
                    var v = (int)a;
                    parts.Add((byte)'I');
                    AddAll(parts, BitConverter.GetBytes(v));
                }
                else if (a is string)
                {
                    var v = (string)a;
                    parts.Add((byte)'S');
                    parts.Add((byte)v.Length);
                    AddAll(parts, Encoding.UTF8.GetBytes(v));
                }
                else if (a is double)
                {
                    var v = (double)a;
                    parts.Add((byte)'D');
                    AddAll(parts, BitConverter.GetBytes(v));
                }
                else if (a is float)
                {
                    var v = (float)a;
                    parts.Add((byte)'F');
                    AddAll(parts, BitConverter.GetBytes(v));
                }
                else if (a is bool)
                {
                    var v = (bool)a;
                    parts.Add((byte)'B');
                    parts.Add((byte)(v ? 1 : 0));
                }
                else if (a is byte)
                {
                    var v = (byte)a;
                    parts.Add((byte)'b');
                    parts.Add(v);
                }
                else
                {
                    throw new NotSupportedException("Type not supported: " + a.GetType());
                }
            }

                        #if MF_FRAMEWORK_VERSION_V4_3
            return((byte[])parts.ToArray(typeof(byte)));
                        #else
            return(parts.ToArray());
                        #endif
        }
        public override System.Collections.ICollection Scan()
        {
            System.Collections.ArrayList result = new System.Collections.ArrayList();

            DateTime dt = DateTime.Now.AddDays(-Days);


            WorkflowProvider wProvider = Sitecore.Context.ContentDatabase.WorkflowProvider as WorkflowProvider;

            if (wProvider == null)
            {
                return(result);
            }

            string stConnection =
                Sitecore.Configuration.Settings.GetConnectionString(Sitecore.Context.ContentDatabase.Name);

            SqlConnection conn    = null;
            SqlCommand    command = null;
            SqlDataReader reader  = null;

            try
            {
                conn                = new SqlConnection(stConnection);
                command             = conn.CreateCommand();
                command.CommandText = "SELECT DISTINCT ItemID FROM WorkflowHistory WHERE Date > @date";
                command.Parameters.Add(
                    new SqlParameter("@date", System.Data.SqlDbType.DateTime)).Value = dt;

                conn.Open();
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Guid gId = reader.GetGuid(0);

                    Item item = Sitecore.Context.ContentDatabase.GetItem(new Sitecore.Data.ID(gId));

                    foreach (var wEvent in wProvider.HistoryStore.GetHistory(item).Where(hi => hi.Date > dt && hi.NewState != hi.OldState))
                    {
                        WorkflowEventCustom wec = new WorkflowEventCustom(item, wEvent);
                        result.Add(wec);
                    }
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(ex.Message, this);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (conn != null)
                {
                    conn.Close();
                }
            }

            return(result);
        }
Example #48
0
        // Import Of PriceList
        private void ImportingOfPriceList(DataTable PriceList, int IDOfReception)
        {
            //
            // Converting UInt32 In Int32
            //
            PriceList.Columns.Add("ID_PH2", typeof(Int32));
            PriceList.Columns.Add("ID_PR2", typeof(Int32));
            //
            foreach (DataRow CurrentRow in PriceList.Rows)
            {
                //
                try
                {
                    CurrentRow["ID_PH2"] = Convert.ToInt32(CurrentRow["ID_PH"]);
                    CurrentRow["ID_PR2"] = Convert.ToInt32(CurrentRow["ID_PR"]);
                }
                catch { this.RecordingInLogFile("Ошибка при конвертации ID_PH and ID_PR"); }
            }
            //
            try
            {
                if (PriceList.PrimaryKey.Length != 0)
                {
                    PriceList.PrimaryKey = new DataColumn[2] {
                        PriceList.Columns["ID_PH2"], PriceList.Columns["ID_PR2"]
                    }
                }
                ;
            }
            catch { this.RecordingInLogFile("asl"); }
            //
            PriceList.Columns.Remove("ID_PH");
            PriceList.Columns.Remove("ID_PR");
            //
            PriceList.Columns["ID_PH2"].ColumnName = "ID_PH";
            PriceList.Columns["ID_PR2"].ColumnName = "ID_PR";
            //
            // Converting Null And DBNUll in 0
            //
            foreach (DataRow CurrentPrice in PriceList.Rows)
            {
                if ((CurrentPrice["Price"] == null) || (CurrentPrice["Price"] is DBNull))
                {
                    CurrentPrice["Price"] = 0;
                }
            }
            //
            // Getting IDs Of Drugstores
            //
            DataTable TableOfIDsOfDrugstores = new DataView(PriceList).ToTable(true, "ID_PH");

            int[] IDsOfDrugstores = new int[TableOfIDsOfDrugstores.Rows.Count];
            for (int i = 0; i < IDsOfDrugstores.Length; i++)
            {
                IDsOfDrugstores[i] = (int)TableOfIDsOfDrugstores.Rows[i]["ID_PH"];
            }
            //
            // Checking Existence Of Drugstores
            //
            System.Collections.ArrayList CheckedIDs = new System.Collections.ArrayList();
            foreach (int CurrentID in IDsOfDrugstores)
            {
                if (DrugstoreIsActive(CurrentID))
                {
                    CheckedIDs.Add(CurrentID);
                }
            }
            IDsOfDrugstores = new int[0];
            IDsOfDrugstores = (int[])CheckedIDs.ToArray(typeof(int));
            //
            // Recording In Reports Of Importing
            //
            bool Successful = true;

            foreach (int CurrentID in IDsOfDrugstores)
            {
                Successful = RecordingInReportsOfImporting(CurrentID, IDOfReception); if (!Successful)
                {
                    break;
                }
            }
            //
            // Importing Of Drugstores
            //
            //int CountOfImporting = 0;
            DataView GettingDrugstore = new DataView(PriceList);

            for (int i = 0; ((i < IDsOfDrugstores.Length) && Successful); i++)
            {
                //
                // Getting Prices Of Drugstore
                //
                GettingDrugstore.RowFilter = String.Format("ID_PH={0}", IDsOfDrugstores[i]);
                DataTable PricesOfDrugstore = GettingDrugstore.ToTable("PricesOfDrugstore");
                //
                // Addition Of TMP Of ID Of Prices
                //
                PricesOfDrugstore.Columns.Add(new DataColumn("ID", typeof(int)));
                for (int i2 = 0; i2 < PricesOfDrugstore.Rows.Count; i2++)
                {
                    PricesOfDrugstore.Rows[i2]["ID"] = (i2 + 1);
                }
                PricesOfDrugstore.PrimaryKey = new DataColumn[1] {
                    PricesOfDrugstore.Columns["ID"]
                };
                //
                // Filling ID Of Prices And ID_PR Of Products
                //
                int[,] IDAndIDPROfPrices = new int[PricesOfDrugstore.Rows.Count, 2];
                for (int i2 = 0; i2 <= IDAndIDPROfPrices.GetUpperBound(0); i2++)
                {
                    IDAndIDPROfPrices[i2, 0] = (int)PricesOfDrugstore.Rows[i2]["ID"];
                    IDAndIDPROfPrices[i2, 1] = (int)PricesOfDrugstore.Rows[i2]["ID_PR"];
                }
                //
                // Search And Liquidation Of Recurrences
                //
                for (int i2 = 0; i2 <= IDAndIDPROfPrices.GetUpperBound(0); i2++)
                {
                    for (int i3 = 0; i3 <= IDAndIDPROfPrices.GetUpperBound(0); i3++)
                    {
                        if ((i2 != i3) && (i2 > i3) && (IDAndIDPROfPrices[i2, 1] == IDAndIDPROfPrices[i3, 1]))
                        {
                            DataRow GetRow = PricesOfDrugstore.Rows.Find(IDAndIDPROfPrices[i3, 0]);
                            if (GetRow != null)
                            {
                                GetRow.Delete();
                            }
                        }
                    }
                }
                //
                PricesOfDrugstore.AcceptChanges();
                //
                // Getting AllPrices From Drugstore
                //
                bool AllPrices = false;
                for (int i2 = 0; i2 < PricesOfDrugstore.Rows.Count; i2++)
                {
                    if (!(PricesOfDrugstore.Rows[i2]["AllPrices"] is DBNull))
                    {
                        if ((bool)PricesOfDrugstore.Rows[i2]["AllPrices"])
                        {
                            AllPrices = true; break;
                        }
                    }
                }
                //
                // Recording In Reports Of Importing Of PriceList
                //
                UpdatingReportsOfImporting(
                    IDsOfDrugstores[i], IDOfReception, PricesOfDrugstore.Rows.Count, AllPrices);
                //
                // Clearing Columns Of Drugstore
                //
                DataView FilteringOfColumns = new DataView(PricesOfDrugstore);
                PricesOfDrugstore =
                    FilteringOfColumns.ToTable(
                        "PricesOfDrugstore", true, "ID_PR", "Price", "Deleting", "Preferential");
                PricesOfDrugstore.PrimaryKey = new DataColumn[] { PricesOfDrugstore.Columns["ID_PR"] };
                //
                // Importing Of Prices Of Drugstore
                //
                ImportingOfPricesOfDrugstore(IDOfReception, IDsOfDrugstores[i], AllPrices, PricesOfDrugstore);
                //
            }
        }
Example #49
0
        private void ParseFieldList(string FieldList, bool AllowRelation)
        {
            /*
             * This code parses FieldList into FieldInfo objects  and then
             * adds them to the m_FieldInfo private member
             *
             * FieldList systax:  [relationname.]fieldname[ alias], ...
             */
            if (m_FieldList == FieldList)
            {
                return;
            }
            m_FieldInfo = new System.Collections.ArrayList();
            m_FieldList = FieldList;
            FieldInfo Field; string[] FieldParts; string[] Fields = FieldList.Split(',');
            int       i;

            for (i = 0; i <= Fields.Length - 1; i++)
            {
                Field = new FieldInfo();
                //parse FieldAlias
                FieldParts = Fields[i].Trim().Split(' ');
                switch (FieldParts.Length)
                {
                case 1:
                    //to be set at the end of the loop
                    break;

                case 2:
                    Field.FieldAlias = FieldParts[1];
                    break;

                default:
                    throw new Exception("Too many spaces in field definition: '" + Fields[i] + "'.");
                }
                //parse FieldName and RelationName
                FieldParts = FieldParts[0].Split('.');
                switch (FieldParts.Length)
                {
                case 1:
                    Field.FieldName = FieldParts[0];
                    break;

                case 2:
                    if (AllowRelation == false)
                    {
                        throw new Exception("Relation specifiers not permitted in field list: '" + Fields[i] + "'.");
                    }
                    Field.RelationName = FieldParts[0].Trim();
                    Field.FieldName    = FieldParts[1].Trim();
                    break;

                default:
                    throw new Exception("Invalid field definition: " + Fields[i] + "'.");
                }
                if (Field.FieldAlias == null)
                {
                    Field.FieldAlias = Field.FieldName;
                }
                m_FieldInfo.Add(Field);
            }
        }
Example #50
0
 /// <summary> Adds an element (segment or group) to this group.  </summary>
 public virtual void  addStructure(StructureDef s)
 {
     elements.Add(s);
 }
Example #51
0
        public SchemaParser(System.String aString)
        {
            InitBlock();

            int index;

            if ((index = aString.IndexOf((System.Char) '\\')) != -1)
            {
                /*
                 * Unless we escape the slash, StreamTokenizer will interpret the
                 * single slash and convert it assuming octal values.
                 * Two successive back slashes are intrepreted as one backslash.
                 */
                System.Text.StringBuilder newString = new System.Text.StringBuilder(aString.Substring(0, (index) - (0)));
                for (int i = index; i < aString.Length; i++)
                {
                    newString.Append(aString[i]);
                    if (aString[i] == '\\')
                    {
                        newString.Append('\\');
                    }
                }
                rawString = newString.ToString();
            }
            else
            {
                rawString = aString;
            }

            SchemaTokenCreator st2 = new SchemaTokenCreator(new System.IO.StringReader(rawString));

            st2.OrdinaryCharacter('.');
            st2.OrdinaryCharacters('0', '9');
            st2.OrdinaryCharacter('{');
            st2.OrdinaryCharacter('}');
            st2.OrdinaryCharacter('_');
            st2.OrdinaryCharacter(';');
            st2.WordCharacters('.', '9');
            st2.WordCharacters('{', '}');
            st2.WordCharacters('_', '_');
            st2.WordCharacters(';', ';');
            //First parse out the OID
            try
            {
                System.String currName;
                if ((int)TokenTypes.EOF != st2.nextToken())
                {
                    if (st2.lastttype == '(')
                    {
                        if ((int)TokenTypes.WORD == st2.nextToken())
                        {
                            id = st2.StringValue;
                        }
                        while ((int)TokenTypes.EOF != st2.nextToken())
                        {
                            if (st2.lastttype == (int)TokenTypes.WORD)
                            {
                                if (st2.StringValue.ToUpper().Equals("NAME".ToUpper()))
                                {
                                    if (st2.nextToken() == '\'')
                                    {
                                        names    = new System.String[1];
                                        names[0] = st2.StringValue;
                                    }
                                    else
                                    {
                                        if (st2.lastttype == '(')
                                        {
                                            System.Collections.ArrayList nameList = new System.Collections.ArrayList();
                                            while (st2.nextToken() == '\'')
                                            {
                                                if ((System.Object)st2.StringValue != null)
                                                {
                                                    nameList.Add(st2.StringValue);
                                                }
                                            }
                                            if (nameList.Count > 0)
                                            {
                                                names = new System.String[nameList.Count];
                                                SupportClass.ArrayListSupport.ToArray(nameList, names);
                                            }
                                        }
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("DESC".ToUpper()))
                                {
                                    if (st2.nextToken() == '\'')
                                    {
                                        description = st2.StringValue;
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("SYNTAX".ToUpper()))
                                {
                                    result = st2.nextToken();
                                    if ((result == (int)TokenTypes.WORD) || (result == '\''))
                                    //Test for non-standard schema
                                    {
                                        syntax = st2.StringValue;
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("EQUALITY".ToUpper()))
                                {
                                    if (st2.nextToken() == (int)TokenTypes.WORD)
                                    {
                                        equality = st2.StringValue;
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("ORDERING".ToUpper()))
                                {
                                    if (st2.nextToken() == (int)TokenTypes.WORD)
                                    {
                                        ordering = st2.StringValue;
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("SUBSTR".ToUpper()))
                                {
                                    if (st2.nextToken() == (int)TokenTypes.WORD)
                                    {
                                        substring = st2.StringValue;
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("FORM".ToUpper()))
                                {
                                    if (st2.nextToken() == (int)TokenTypes.WORD)
                                    {
                                        nameForm = st2.StringValue;
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("OC".ToUpper()))
                                {
                                    if (st2.nextToken() == (int)TokenTypes.WORD)
                                    {
                                        objectClass = st2.StringValue;
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("SUP".ToUpper()))
                                {
                                    System.Collections.ArrayList values = new System.Collections.ArrayList();
                                    st2.nextToken();
                                    if (st2.lastttype == '(')
                                    {
                                        st2.nextToken();
                                        while (st2.lastttype != ')')
                                        {
                                            if (st2.lastttype != '$')
                                            {
                                                values.Add(st2.StringValue);
                                            }
                                            st2.nextToken();
                                        }
                                    }
                                    else
                                    {
                                        values.Add(st2.StringValue);
                                        superior = st2.StringValue;
                                    }
                                    if (values.Count > 0)
                                    {
                                        superiors = new System.String[values.Count];
                                        SupportClass.ArrayListSupport.ToArray(values, superiors);
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("SINGLE-VALUE".ToUpper()))
                                {
                                    single = true;
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("OBSOLETE".ToUpper()))
                                {
                                    obsolete = true;
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("COLLECTIVE".ToUpper()))
                                {
                                    collective = true;
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("NO-USER-MODIFICATION".ToUpper()))
                                {
                                    userMod = false;
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("MUST".ToUpper()))
                                {
                                    System.Collections.ArrayList values = new System.Collections.ArrayList();
                                    st2.nextToken();
                                    if (st2.lastttype == '(')
                                    {
                                        st2.nextToken();
                                        while (st2.lastttype != ')')
                                        {
                                            if (st2.lastttype != '$')
                                            {
                                                values.Add(st2.StringValue);
                                            }
                                            st2.nextToken();
                                        }
                                    }
                                    else
                                    {
                                        values.Add(st2.StringValue);
                                    }
                                    if (values.Count > 0)
                                    {
                                        required = new System.String[values.Count];
                                        SupportClass.ArrayListSupport.ToArray(values, required);
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("MAY".ToUpper()))
                                {
                                    System.Collections.ArrayList values = new System.Collections.ArrayList();
                                    st2.nextToken();
                                    if (st2.lastttype == '(')
                                    {
                                        st2.nextToken();
                                        while (st2.lastttype != ')')
                                        {
                                            if (st2.lastttype != '$')
                                            {
                                                values.Add(st2.StringValue);
                                            }
                                            st2.nextToken();
                                        }
                                    }
                                    else
                                    {
                                        values.Add(st2.StringValue);
                                    }
                                    if (values.Count > 0)
                                    {
                                        optional = new System.String[values.Count];
                                        SupportClass.ArrayListSupport.ToArray(values, optional);
                                    }
                                    continue;
                                }

                                if (st2.StringValue.ToUpper().Equals("NOT".ToUpper()))
                                {
                                    System.Collections.ArrayList values = new System.Collections.ArrayList();
                                    st2.nextToken();
                                    if (st2.lastttype == '(')
                                    {
                                        st2.nextToken();
                                        while (st2.lastttype != ')')
                                        {
                                            if (st2.lastttype != '$')
                                            {
                                                values.Add(st2.StringValue);
                                            }
                                            st2.nextToken();
                                        }
                                    }
                                    else
                                    {
                                        values.Add(st2.StringValue);
                                    }
                                    if (values.Count > 0)
                                    {
                                        precluded = new System.String[values.Count];
                                        SupportClass.ArrayListSupport.ToArray(values, precluded);
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("AUX".ToUpper()))
                                {
                                    System.Collections.ArrayList values = new System.Collections.ArrayList();
                                    st2.nextToken();
                                    if (st2.lastttype == '(')
                                    {
                                        st2.nextToken();
                                        while (st2.lastttype != ')')
                                        {
                                            if (st2.lastttype != '$')
                                            {
                                                values.Add(st2.StringValue);
                                            }
                                            st2.nextToken();
                                        }
                                    }
                                    else
                                    {
                                        values.Add(st2.StringValue);
                                    }
                                    if (values.Count > 0)
                                    {
                                        auxiliary = new System.String[values.Count];
                                        SupportClass.ArrayListSupport.ToArray(values, auxiliary);
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("ABSTRACT".ToUpper()))
                                {
                                    type = LdapObjectClassSchema.ABSTRACT;
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("STRUCTURAL".ToUpper()))
                                {
                                    type = LdapObjectClassSchema.STRUCTURAL;
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("AUXILIARY".ToUpper()))
                                {
                                    type = LdapObjectClassSchema.AUXILIARY;
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("USAGE".ToUpper()))
                                {
                                    if (st2.nextToken() == (int)TokenTypes.WORD)
                                    {
                                        currName = st2.StringValue;
                                        if (currName.ToUpper().Equals("directoryOperation".ToUpper()))
                                        {
                                            usage = LdapAttributeSchema.DIRECTORY_OPERATION;
                                        }
                                        else if (currName.ToUpper().Equals("distributedOperation".ToUpper()))
                                        {
                                            usage = LdapAttributeSchema.DISTRIBUTED_OPERATION;
                                        }
                                        else if (currName.ToUpper().Equals("dSAOperation".ToUpper()))
                                        {
                                            usage = LdapAttributeSchema.DSA_OPERATION;
                                        }
                                        else if (currName.ToUpper().Equals("userApplications".ToUpper()))
                                        {
                                            usage = LdapAttributeSchema.USER_APPLICATIONS;
                                        }
                                    }
                                    continue;
                                }
                                if (st2.StringValue.ToUpper().Equals("APPLIES".ToUpper()))
                                {
                                    System.Collections.ArrayList values = new System.Collections.ArrayList();
                                    st2.nextToken();
                                    if (st2.lastttype == '(')
                                    {
                                        st2.nextToken();
                                        while (st2.lastttype != ')')
                                        {
                                            if (st2.lastttype != '$')
                                            {
                                                values.Add(st2.StringValue);
                                            }
                                            st2.nextToken();
                                        }
                                    }
                                    else
                                    {
                                        values.Add(st2.StringValue);
                                    }
                                    if (values.Count > 0)
                                    {
                                        applies = new System.String[values.Count];
                                        SupportClass.ArrayListSupport.ToArray(values, applies);
                                    }
                                    continue;
                                }
                                currName = st2.StringValue;
                                AttributeQualifier q = parseQualifier(st2, currName);
                                if (q != null)
                                {
                                    qualifiers.Add(q);
                                }
                                continue;
                            }
                        }
                    }
                }
            }
            catch (System.IO.IOException e)
            {
                throw e;
            }
        }
Example #52
0
        /// <summary> Interleave "bits" with corresponding error correction bytes. On success, store the result in
        /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.
        /// </summary>
        internal static void  interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result)
        {
            // "bits" must have "getNumDataBytes" bytes of data.
            if (bits.sizeInBytes() != numDataBytes)
            {
                throw new WriterException("Number of bits and data bytes does not match");
            }

            // Step 1.  Divide data bytes into blocks and generate error correction bytes for them. We'll
            // store the divided data bytes blocks and error correction bytes blocks into "blocks".
            int dataBytesOffset = 0;
            int maxNumDataBytes = 0;
            int maxNumEcBytes   = 0;

            // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.
            System.Collections.ArrayList blocks = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(numRSBlocks));

            for (int i = 0; i < numRSBlocks; ++i)
            {
                int[] numDataBytesInBlock = new int[1];
                int[] numEcBytesInBlock   = new int[1];
                getNumDataBytesAndNumECBytesForBlockID(numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock);

                ByteArray dataBytes = new ByteArray();
                dataBytes.set_Renamed(bits.Array, dataBytesOffset, numDataBytesInBlock[0]);
                ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]);
                blocks.Add(new BlockPair(dataBytes, ecBytes));

                maxNumDataBytes  = System.Math.Max(maxNumDataBytes, dataBytes.size());
                maxNumEcBytes    = System.Math.Max(maxNumEcBytes, ecBytes.size());
                dataBytesOffset += numDataBytesInBlock[0];
            }
            if (numDataBytes != dataBytesOffset)
            {
                throw new WriterException("Data bytes does not match offset");
            }

            // First, place data blocks.
            for (int i = 0; i < maxNumDataBytes; ++i)
            {
                for (int j = 0; j < blocks.Count; ++j)
                {
                    ByteArray dataBytes = ((BlockPair)blocks[j]).DataBytes;
                    if (i < dataBytes.size())
                    {
                        result.appendBits(dataBytes.at(i), 8);
                    }
                }
            }
            // Then, place error correction blocks.
            for (int i = 0; i < maxNumEcBytes; ++i)
            {
                for (int j = 0; j < blocks.Count; ++j)
                {
                    ByteArray ecBytes = ((BlockPair)blocks[j]).ErrorCorrectionBytes;
                    if (i < ecBytes.size())
                    {
                        result.appendBits(ecBytes.at(i), 8);
                    }
                }
            }
            if (numTotalBytes != result.sizeInBytes())
            {
                // Should be same.
                throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ.");
            }
        }
Example #53
0
 /// <summary>
 /// Add a Service Class Id.
 /// </summary>
 /// -
 /// <remarks>
 /// <para>Multiple class ids can be added, and they will be written to the
 /// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ServiceClassIdList"/>
 /// attribute in the order in which they were set.
 /// </para>
 /// </remarks>
 /// -
 /// <param name="uuid128">A <see cref="T:System.Guid"/> containing a
 /// UUID for the advertised service.
 /// </param>
 public void AddServiceClass(Guid uuid128)
 {
     m_classIds.Add(uuid128);
 }
        protected new void carregaTypDatSet()
        {
            try
            {
                mdlDataBaseAccess.Tabelas.XsdTbInstrucoesEmbarque.tbInstrucoesEmbarqueRow dtrwRowTbInstrucoesEmbarque;
                mdlDataBaseAccess.Tabelas.XsdTbFaturasComerciais.tbFaturasComerciaisRow   dtrwRowTbFaturasComerciais;
                System.Collections.ArrayList arlCondicaoCampo      = new System.Collections.ArrayList();
                System.Collections.ArrayList arlCondicaoComparador = new System.Collections.ArrayList();
                System.Collections.ArrayList arlCondicaoValor      = new System.Collections.ArrayList();

                arlCondicaoCampo.Add("idExportador");
                arlCondicaoComparador.Add(mdlDataBaseAccess.Comparador.Igual);
                arlCondicaoValor.Add(m_nIdExportador);

                m_typDatSetTbExportadores = m_cls_dba_ConnectionBD.GetTbExportadores(arlCondicaoCampo, arlCondicaoComparador, arlCondicaoValor, null, null);

                arlCondicaoCampo.Add("idPE");
                arlCondicaoComparador.Add(mdlDataBaseAccess.Comparador.Igual);
                arlCondicaoValor.Add(m_strIdPE);

                m_typDatSetTbInstrucoesEmbarque = m_cls_dba_ConnectionBD.GetTbInstrucoesEmbarque(arlCondicaoCampo, arlCondicaoComparador, arlCondicaoValor, null, null);
                m_typDatSetTbFaturasComerciais  = m_cls_dba_ConnectionBD.GetTbFaturasComerciais(arlCondicaoCampo, arlCondicaoComparador, arlCondicaoValor, null, null);;
                if (m_typDatSetTbInstrucoesEmbarque.tbInstrucoesEmbarque.Rows.Count > 0)
                {
                    dtrwRowTbInstrucoesEmbarque = (mdlDataBaseAccess.Tabelas.XsdTbInstrucoesEmbarque.tbInstrucoesEmbarqueRow)m_typDatSetTbInstrucoesEmbarque.tbInstrucoesEmbarque.Rows[0];
                    if (!dtrwRowTbInstrucoesEmbarque.IsdtDataEmissaoNull())
                    {
                        m_dtData = dtrwRowTbInstrucoesEmbarque.dtDataEmissao;
                    }
                    if (!dtrwRowTbInstrucoesEmbarque.IsstrNumeroNull())
                    {
                        m_strNumero = dtrwRowTbInstrucoesEmbarque.strNumero.Replace("\0", "");
                    }
                }
                if (m_typDatSetTbFaturasComerciais.tbFaturasComerciais.Rows.Count > 0)
                {
                    dtrwRowTbFaturasComerciais = (mdlDataBaseAccess.Tabelas.XsdTbFaturasComerciais.tbFaturasComerciaisRow)m_typDatSetTbFaturasComerciais.tbFaturasComerciais.Rows[0];
                    if (!dtrwRowTbFaturasComerciais.IsidImportadorNull())
                    {
                        m_nIdImportador = dtrwRowTbFaturasComerciais.idImportador;
                    }
                }

                arlCondicaoCampo.Clear();
                arlCondicaoComparador.Clear();
                arlCondicaoValor.Clear();

                arlCondicaoCampo.Add("idExportador");
                arlCondicaoComparador.Add(mdlDataBaseAccess.Comparador.Igual);
                arlCondicaoValor.Add(m_nIdExportador);
                arlCondicaoCampo.Add("idImportador");
                arlCondicaoComparador.Add(mdlDataBaseAccess.Comparador.Igual);
                arlCondicaoValor.Add(m_nIdImportador);

                m_typDatSetTbImportadores = m_cls_dba_ConnectionBD.GetTbImportadores(arlCondicaoCampo, arlCondicaoComparador, arlCondicaoValor, null, null);
            }
            catch (Exception err)
            {
                Object erro = err;
                m_cls_ter_tratadorErro.trataErro(ref erro);
            }
        }
Example #55
0
        /// <summary>
        /// 将表达式转换为实际的值
        /// </summary>
        internal void ExplainValues()
        {
            System.Text.StringBuilder    mySql  = new System.Text.StringBuilder();
            System.Collections.ArrayList myItem = new System.Collections.ArrayList();
            string Flag = null;

            foreach (Argument item in this.myHashtable.Values)
            {
                if (item.IsUpdate || !item.IsExpression)
                {
                    continue;
                }
                string Value = item._Value;
                if (Value == null)
                {
                    return;
                }

                //SQL语句
                if (Value.ToUpper().TrimStart().StartsWith("SQL:"))
                {
                    Value = this.ParentReport.ExplainArgument(item._Value);
                    string Sql = Value.Substring("SQL:".Length);
                    if (Sql.TrimStart().ToUpper().StartsWith("SELECT"))
                    {
                        mySql.Append(Sql);              mySql.Append(";");
                        myItem.Add(item.Name);
                        Flag = "SQL";
                    }
                    else
                    {
                        item.IsUpdate = true;
                    }
                }
            }

            try
            {
                switch (Flag)
                {
                case "SQL":
                {
                    //执行命令并获取值:SQL语句
                    if (mySql.Length != 0 && this.ParentReport != null && this.ParentReport.DbConnection != null)
                    {
                        this.ParentReport.DbCommand.CommandText = mySql.ToString();
                        if (this.ParentReport is ReportDetail)
                        {
                            (this.ParentReport as ReportDetail).AppendParameters();
                        }
                        System.Data.IDataReader myReader = this.ParentReport.DbCommand.ExecuteReader();

                        foreach (string name in myItem)
                        {
                            Argument myArgument = this.myHashtable[name.ToLower()] as Argument;
                            if (myReader.Read())
                            {
                                myArgument.Value    = myReader[0] == null?"":myReader[0].ToString();
                                myArgument.IsUpdate = true;
                            }
                            if (!myReader.NextResult())
                            {
                                break;
                            }
                        }

                        myReader.Close();
                    }
                }
                break;

                default:                                //普通表达式
                {
                }
                break;
                }
            }
            catch (Exception myExp)
            {
                throw new ReportException(myExp.Message, myExp);
            }
        }
Example #56
0
        static void Main(string[] args)
        {
            //15가지 기본자료 형식

            //정수타입 예제
            sbyte a = -10;
            byte  b = 40;

            WriteLine($"a = {a}, b = {b}");
            WriteLine($"a type = {a.GetType()}, b type = {b.GetType()}");
            WriteLine($"a max = {sbyte.MaxValue} , a min = {sbyte.MinValue}");
            WriteLine($"b max = {byte.MaxValue} , b min = {byte.MinValue}");
            WriteLine();
            short  c = -30000;
            ushort d = 60000;

            WriteLine($"c = {c}, d = {d}");
            WriteLine($"c type = {c.GetType()}, d type = {d.GetType()}");
            WriteLine($"c max = {short.MaxValue}, c min = {short.MinValue}");
            WriteLine($"d max = {ushort.MaxValue}, d max = {ushort.MinValue}");
            WriteLine();

            int  e = -1000_0000;
            uint f = 3_0000_0000;

            WriteLine($"e = {e}, f = {f}");
            WriteLine($"e type = {e.GetType()}, f type = {f.GetType()}");
            WriteLine($"e max = {int.MaxValue} , e min = {int.MinValue}");
            WriteLine($"f max = {uint.MaxValue}, f min = {uint.MinValue}");
            WriteLine();

            long  g = -5000_0000_0000;
            ulong h = 200_0000_0000_0000_0000;

            WriteLine($"g = {g}, h = {h}");
            WriteLine($"g type = {g.GetType()}, h type = {h.GetType()}");
            WriteLine($"g max = {long.MaxValue} , g min = {long.MinValue}");
            WriteLine($"h max = {ulong.MaxValue} , h min = {ulong.MinValue}");
            WriteLine();
            WriteLine();
            //2진수 10진수 16진수
            byte b_a = 240;                             //10
            byte b_b = 0b11110000;                      //2
            byte b_c = 0xF0;                            //16
            uint b_d = 0x1234abcd;

            WriteLine($"b_a = {b_a}, b_b ={b_b}, b_c={b_c}, b_d = {b_d}");

            WriteLine();
            WriteLine();
            //부동 소수점 형식
            float   c_a = 3.14159265358979323846f;
            double  c_b = 3.14159265358979323846;
            decimal c_c = 3.141592653589793238462643383279m;

            WriteLine($"c_a = {c_a} , c_b = {c_b} , c_c = {c_c}");


            WriteLine();
            WriteLine();
            //문자형식과 문자열
            char d_a = 'a';
            char d_b = 'e';
            char d_c = 'i';
            char d_d = 'o';
            char d_e = 'u';

            Write(d_a);
            Write(d_b);
            Write(d_c);
            Write(d_d);
            Write(d_e);
            WriteLine();

            string e_a = "aeiou";

            WriteLine(e_a);

            WriteLine();
            WriteLine();
            //논리형식
            bool f_a = true;
            bool f_b = false;

            WriteLine($"f_a = {f_a} , f_b = {f_b}");


            WriteLine();
            WriteLine();
            //object
            object g_a = 123;
            object g_b = 3.141592653589793238462643383279m;
            object g_c = true;
            object g_d = "안녕하세여";

            WriteLine($"g_a = {g_a} , g_b = {g_b} , g_c = {g_c} , g_d = {g_d}");


            WriteLine();
            WriteLine();
            //박싱 언박싱
            int    h_a = 123;
            object h_b = (object)h_a;
            int    h_c = (int)h_b;

            WriteLine($"h_a = {h_a} , h_b = {h_b} , h_c = {h_c}");


            WriteLine();
            WriteLine();
            //문자열을 숫자, 숫자를 문자열
            int    i_a = 123;
            string i_b = i_a.ToString();

            WriteLine($"i_a = {i_a}, {i_a.GetType()} , i_b = {i_b}, {i_b.GetType()}");

            float  i_c = 3.14f;
            string i_d = i_c.ToString();

            WriteLine($"i_c = {i_c}, {i_c.GetType()} , i_d = {i_d}, {i_d.GetType()}");

            string i_e = "123456";
            int    i_f = Convert.ToInt32(i_e);

            WriteLine($"i_e = {i_e}, {i_e.GetType()} , i_f = {i_f}, {i_f.GetType()}");

            i_f = int.Parse(i_e);
            WriteLine($"i_e = {i_e}, {i_e.GetType()} , i_f = {i_f}, {i_f.GetType()}");

            string i_g = "1.23456";
            float  i_h = float.Parse(i_g);

            WriteLine($"i_g = {i_g}, {i_g.GetType()} , i_h = {i_h}, {i_h.GetType()}");

            WriteLine();
            WriteLine();
            //널 조건부 연산자
            System.Collections.ArrayList check = null;
            check?.Add("야구");
            check?.Add("축구");
            WriteLine($"count : {check?.Count}");
            WriteLine($"{check?[0]}");
            WriteLine($"{check?[1]}");

            check = new System.Collections.ArrayList();
            check?.Add("야구");
            check?.Add("축구");
            WriteLine($"count : {check?.Count}");
            WriteLine($"{check?[0]}");
            WriteLine($"{check?[1]}");


            WriteLine();
            WriteLine();
            //널 병합 연산자
            int?num = null;

            WriteLine($"{num ?? -1}");

            num = 50;
            WriteLine($"{num ?? -1}");

            string tmp = null;

            WriteLine($"{tmp ?? "def"}");

            tmp = "a";
            WriteLine($"{tmp ?? "def"}");
        }
Example #57
0
        /// <summary>
        /// Получить адрес строкой.
        /// </summary>
        // *** Start programmer edit section *** (Prozhivanie.AdresStrokoi CustomAttributes)
        private string ПолучитьАдресСтрокой(Prozhivanie адрес)
        {
            if (адрес == null || адрес.GetStatus() == ObjectStatus.Created)
            {
                return("");
            }
            string адр = "";

            if (!адрес.CheckLoadedProperty("Territoriia") || !адрес.CheckLoadedProperty("Ulitca") ||
                !адрес.CheckLoadedProperty("PochtIndeks") || !адрес.CheckLoadedProperty("NomerDoma") ||
                !адрес.CheckLoadedProperty("NomerStroeniia") || !адрес.CheckLoadedProperty("Kvartira"))
            {
                DataServiceProvider.DataService.LoadObject(адрес);
            }
            Territoriia тер = адрес.Territoriia;

            if (!тер.CheckLoadedProperty("Ierarhiia") || !тер.CheckLoadedProperty("GorRaion") || !тер.CheckLoadedProperty("VidObekta") ||
                !тер.CheckLoadedProperty("Naimenovanie"))
            {
                DataServiceProvider.DataService.LoadObject(тер);
            }

            System.Collections.ArrayList arl = new System.Collections.ArrayList();
            while (тер.Ierarhiia != null)
            {
                if (тер.GorRaion != tLogicheskii.Da)
                {
                    arl.Add(тер);
                }
                тер = тер.Ierarhiia;
                if (!тер.CheckLoadedProperty("Ierarhiia") || !тер.CheckLoadedProperty("GorRaion") || !тер.CheckLoadedProperty("VidObekta") ||
                    !тер.CheckLoadedProperty("Naimenovanie"))
                {
                    DataServiceProvider.DataService.LoadObject(тер);
                }
            }
            arl.Add(тер);
            Array ar = arl.ToArray();

            for (int i = ar.Length - 1; i >= 0; i--)
            {
                тер = (Territoriia)ar.GetValue(i);
                if (ar.Length == 1)
                {
                    адр = тер.Naimenovanie + (тер.VidObekta == null ? "" : " " + тер.VidObekta.ToLower()) + "., " + адрес.PochtIndeks;
                }
                else
                {
                    if (i == 0)
                    {
                        адр = (адр == "" ? "" : адр + ", ") + адрес.PochtIndeks + ", " + (тер.VidObekta == null ? "" : тер.VidObekta.ToLower() + ". ") + тер.Naimenovanie;
                    }
                    else
                    if (тер.Naimenovanie == "Россия")
                    {
                        адр = "";
                    }
                    else
                    {
                        адр = (адр == "" ? "" : адр + ", ") + тер.Naimenovanie + (тер.VidObekta == null ? "" : " " + тер.VidObekta.ToLower());
                    }
                }
            }
            if (адрес.Ulitca != null)
            {
                Ulitca ул = адрес.Ulitca;
                if (!ул.CheckLoadedProperty("VidObekta") || !ул.CheckLoadedProperty("Naimenovanie"))
                {
                    DataServiceProvider.DataService.LoadObject(ул);
                }
                var           видУлицы = ул.VidObekta.ToLower();
                List <string> видыУлицНеСтавитьТочку = new List <string> {
                    "пр-кт", "проезд", "переулок", "городок", "заезд", "проулок", "тракт"
                };
                видУлицы = (видыУлицНеСтавитьТочку.IndexOf(видУлицы) < 0 ? видУлицы + ". " : видУлицы + " ");
                адр      = адр + ", " + (ул.VidObekta == null ? "" : видУлицы) + ул.Naimenovanie;
            }
            адр = адр + (адрес.NomerDoma == 0 ? "" : ", д. " + адрес.NomerDoma.ToString());
            адр = адр + (адрес.NomerStroeniia == null ? "" : "/" + адрес.NomerStroeniia);
            адр = адр + (адрес.Kvartira == null ? "" : ", кв. " + адрес.Kvartira);
            return(адр);
        }
        private void Cargar(StreamReader streamReader, string idEmpresa)
        {
            System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
            DataTable dataTable = new DataTable();
            int       _int;
            Int32     registro = 0;
            Decimal   _decimal;
            String    linea = "";

            char[]   delimitadores = { ';' };
            Conexion conexion      = new Conexion(Empresa);

            conexion.IniciarTransaccion();

            try
            {
                while (linea != null)
                {
                    linea = streamReader.ReadLine();
                    registro++;
                    if (linea != null)
                    {
                        arrayList.Add(linea);
                        string[] datos = linea.Split(delimitadores);
                        if (datos.Length == 5)
                        {
                            if (Decimal.TryParse(datos[1].ToString(), out _decimal))
                            {
                                if (Int32.TryParse(datos[2].ToString(), out _int))
                                {
                                    if (!string.IsNullOrEmpty(datos[3].ToString()))
                                    {
                                        if (!string.IsNullOrEmpty(datos[4].ToString()))
                                        {
                                            int ValideRegistro = 0;
                                            ValideRegistro = Adicionar(idEmpresa, Usuario, datos[0].ToString(), datos[1].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), conexion);
                                            if (ValideRegistro > 0)
                                            {
                                                if (ValideRegistro == 1)
                                                {
                                                    Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "La cedula reportada no esta registrada en las solicitudes de ingreso.");
                                                }
                                                if (ValideRegistro == 2)
                                                {
                                                    Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Este trabajador no tiene contratos activos.");
                                                }
                                                if (ValideRegistro == 3)
                                                {
                                                    Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Este trabajador tiene mas de un contrato activo.");
                                                }
                                                if (ValideRegistro == 9)
                                                {
                                                    Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Error desconocido, consulte con el administrador.");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Inconsistencia: El valor no puede estar vacio, sino existe debe estar en cero(0)");
                                        }
                                    }
                                    else
                                    {
                                        Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Inconsistencia: La cantidad no puede estar vacia, sino existe debe estar en cero(0)");
                                    }
                                }
                                else
                                {
                                    Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Inconsistencia: El concepto no es númerico");
                                }
                            }
                            else
                            {
                                Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Inconsistencia: El número de documento no es númerico");
                            }
                        }
                        else
                        {
                            Adicionar(datos[1].ToString(), datos[0].ToString(), datos[2].ToString(), datos[3].ToString(), datos[4].ToString(), "Inconsistencia: El registro " + registro.ToString() + ", no tienen la cantidad de columnas requerida");
                        }
                    }
                }
                dataTable = Procesar(idEmpresa, Usuario, conexion);
                if (!dataTable.Rows.Count.Equals(0))
                {
                    Cargar(dataTable);
                }
                conexion.AceptarTransaccion();
            }
            catch (Exception e)
            {
                conexion.DeshacerTransaccion();
                throw new Exception(e.Message);
            }
            finally
            {
                conexion.Desconectar();
            }
        }
Example #59
0
 ///<summary>
 ///Adds an using_namespace to the end of the using_namespaceArrayList.
 ///</summary>
 ///<param name="value">The using_namespace to be added to the end of the ArrayList. The value can be a null reference.<param>
 ///<returns>The using_namespaceArrayList index at which the value has been added.</returns>
 public int Add(using_namespace value)
 {
     return(arr.Add(value));
 }
Example #60
0
        private void HandleResponse(object sender, Gtk.ResponseArgs args)
        {
            long new_size = 0;
//			long orig_size = 0;
            long actual_total_size = 0;
            int  size = 0;

            System.IO.FileInfo file_info;
            bool UserCancelled = false;
            bool rotate        = true;

            // Lets remove the mail "create mail" dialog
            Dialog.Destroy();

            if (args.ResponseId != Gtk.ResponseType.Ok)
            {
                return;
            }
            ProgressDialog progress_dialog = null;

            actual_total_size = 0;

            progress_dialog = new ProgressDialog(Catalog.GetString("Preparing email"),
                                                 ProgressDialog.CancelButtonType.Stop,
                                                 selection.Items.Length,
                                                 parent_window);

            size = GetScaleSize();             // Which size should we scale to. 0 --> Original

            // evaluate mailto command and define attachment args for cli
            System.Text.StringBuilder attach_arg = new System.Text.StringBuilder();
            switch (Preferences.Get(Preferences.GNOME_MAILTO_COMMAND) as string)
            {
            case "thunderbird %s":
            case "mozilla-thunderbird %s":
            case "seamonkey -mail -compose %s":
            case "icedove %s":
                attach_arg.Append(",");
                break;

            case "kmail %s":
                attach_arg.Append(" --attach ");
                break;

            default:                      //evolution falls into default, since it supports mailto uri correctly
                attach_arg.Append("&attach=");
                break;
            }

            rotate = rotate_check.Active;              // Should we automatically rotate original photos.
            Preferences.Set(Preferences.EXPORT_EMAIL_ROTATE, rotate);

            // Initiate storage for temporary files to be deleted later
            tmp_paths = new System.Collections.ArrayList();

            // Create a tmp directory.
            tmp_mail_dir = System.IO.Path.GetTempFileName();                    // Create a tmp file
            System.IO.File.Delete(tmp_mail_dir);                                // Delete above tmp file
            System.IO.Directory.CreateDirectory(tmp_mail_dir);                  // Create a directory with above tmp name

            System.Text.StringBuilder mail_attach = new System.Text.StringBuilder();

            FilterSet filters = new FilterSet();

            if (size != 0)
            {
                filters.Add(new ResizeFilter((uint)size));
            }
            else if (rotate)
            {
                filters.Add(new OrientationFilter());
            }
            filters.Add(new UniqueNameFilter(tmp_mail_dir));


            foreach (Photo photo in selection.Items)
            {
                if ((photo != null) && (!UserCancelled))
                {
                    if (progress_dialog != null)
                    {
                        UserCancelled = progress_dialog.Update(String.Format
                                                                   (Catalog.GetString("Exporting picture \"{0}\""), photo.Name));
                    }

                    if (UserCancelled)
                    {
                        break;
                    }

                    file_info = new System.IO.FileInfo(photo.GetVersionPath(photo.DefaultVersionId));
//					orig_size = file_info.Length;

                    // Prepare a tmp_mail file name
                    FilterRequest request = new FilterRequest(photo.DefaultVersionUri);

                    filters.Convert(request);
                    request.Preserve(request.Current);

                    mail_attach.Append(attach_arg.ToString() + System.Web.HttpUtility.UrlEncode(request.Current.ToString()));

                    // Mark the path for deletion
                    tmp_paths.Add(request.Current.LocalPath);

                    // Update the running total of the actual file sizes.
                    file_info          = new System.IO.FileInfo(request.Current.LocalPath);
                    new_size           = file_info.Length;
                    actual_total_size += new_size;

                    // Update dialog to indicate Actual size!
                    // This is currently disabled, since the dialog box is not visible at this stage.
                    // string approxresult = SizeUtil.ToHumanReadable (actual_total_size);
                    // ActualMailSize.Text = approxresult;


                    //System.Console.WriteLine ("Orig file size {0}, New file size {1}, % {4}, Scaled to size {2}, new name {3}",
                    //orig_size, new_size, size, tmp_path, 1 - ((orig_size-new_size)/orig_size));
                }
            }             // foreach

            if (progress_dialog != null)
            {
                progress_dialog.Destroy();                  // No need to keep this window
            }
            if (UserCancelled)
            {
                DeleteTempFile();
            }
            else
            {
                // Send the mail :)
                switch (Preferences.Get(Preferences.GNOME_MAILTO_COMMAND) as string)
                {
                // openSuSE
                case "thunderbird %s":
                    System.Diagnostics.Process.Start("thunderbird", " -compose \"subject=my photos,attachment='" + mail_attach + "'\"");
                    break;

                case "icedove %s":
                    System.Diagnostics.Process.Start("thunderbird", " -compose \"subject=my photos,attachment='" + mail_attach + "'\"");
                    break;

                case "mozilla-thunderbird %s":
                    System.Diagnostics.Process.Start("mozilla-thunderbird", " -compose \"subject=my photos,attachment='" + mail_attach + "'\"");
                    break;

                case "seamonkey -mail -compose %s":
                    System.Diagnostics.Process.Start("seamonkey", " -mail -compose \"subject=my photos,attachment='" + mail_attach + "'\"");
                    break;

                case "kmail %s":
                    System.Diagnostics.Process.Start("kmail", "  --composer --subject \"my photos\"" + mail_attach);
                    break;

                default:
                    GnomeUtil.UrlShow(parent_window, "mailto:?subject=my%20photos" + mail_attach);
                    break;
                }

                // Check if we have any temporary files to be deleted
                if (tmp_paths.Count > 0)
                {
                    // Fetch timeout value from preferences. In seconds. Needs to be multiplied with 1000 to get msec
                    uint delete_timeout;
                    delete_timeout = (uint)((int)Preferences.Get(Preferences.EXPORT_EMAIL_DELETE_TIMEOUT_SEC));
                    delete_timeout = delete_timeout * 1000;                     // to get milliseconds.

                    // Start a timer and when it occurs, delete the temp files.
                    GLib.Timeout.Add(delete_timeout, new GLib.TimeoutHandler(DeleteTempFile));
                }
            }
        }