Add() public méthode

public Add ( Object value ) : int
value Object
Résultat int
        public IResponse Execute(ICruiseRequest request)
        {
            Hashtable velocityContext = new Hashtable();
            ArrayList links = new ArrayList();
            links.Add(new ServerLink(urlBuilder, request.ServerSpecifier, "Server Log", ActionName));

            ProjectStatusListAndExceptions projects = farmService.GetProjectStatusListAndCaptureExceptions(request.ServerSpecifier,
                request.RetrieveSessionToken());
            foreach (ProjectStatusOnServer projectStatusOnServer in projects.StatusAndServerList)
            {
                DefaultProjectSpecifier projectSpecifier = new DefaultProjectSpecifier(projectStatusOnServer.ServerSpecifier, projectStatusOnServer.ProjectStatus.Name);
                links.Add(new ProjectLink(urlBuilder, projectSpecifier, projectSpecifier.ProjectName, ServerLogProjectPlugin.ActionName));
            }
            velocityContext["projectLinks"] = links;
            if (string.IsNullOrEmpty(request.ProjectName))
            {
                velocityContext["log"] = HttpUtility.HtmlEncode(farmService.GetServerLog(request.ServerSpecifier, request.RetrieveSessionToken()));
            }
            else
            {
                velocityContext["currentProject"] = request.ProjectSpecifier.ProjectName;
                velocityContext["log"] = HttpUtility.HtmlEncode(farmService.GetServerLog(request.ProjectSpecifier, request.RetrieveSessionToken()));
            }

            return viewGenerator.GenerateView(@"ServerLog.vm", velocityContext);
        }
		/// <summary>
		/// Creates a NDataReader from a <see cref="IDataReader" />
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader" /> to get the records from the Database.</param>
		/// <param name="isMidstream"><see langword="true" /> if we are loading the <see cref="IDataReader" /> in the middle of reading it.</param>
		/// <remarks>
		/// NHibernate attempts to not have to read the contents of an <see cref="IDataReader"/> into memory until it absolutely
		/// has to.  What that means is that it might have processed some records from the <see cref="IDataReader"/> and will
		/// pick up the <see cref="IDataReader"/> midstream so that the underlying <see cref="IDataReader"/> can be closed 
		/// so a new one can be opened.
		/// </remarks>
		public NDataReader(IDataReader reader, bool isMidstream)
		{
			ArrayList resultList = new ArrayList(2);

			try
			{
				// if we are in midstream of processing a DataReader then we are already
				// positioned on the first row (index=0)
				if (isMidstream)
				{
					currentRowIndex = 0;
				}

				// there will be atleast one result 
				resultList.Add(new NResult(reader, isMidstream));

				while (reader.NextResult())
				{
					// the second, third, nth result is not processed midstream
					resultList.Add(new NResult(reader, false));
				}

				results = (NResult[]) resultList.ToArray(typeof(NResult));
			}
			catch (Exception e)
			{
				throw new ADOException("There was a problem converting an IDataReader to NDataReader", e);
			}
			finally
			{
				reader.Close();
			}
		}
        public DataSet PRC_PersonasListasDePrecios()
        {
            ArrayList Parameters=new ArrayList(0);

            SqlParameter MODOParameter=new SqlParameter("@MODO",SqlDbType.Int);
            MODOParameter.Size=0;
            MODOParameter.Value=MODO;
            Parameters.Add(MODOParameter);

            SqlParameter PersonasListasDePrecios_IDParameter=new SqlParameter("@PersonasListasDePrecios_ID",SqlDbType.Int);
            PersonasListasDePrecios_IDParameter.Size=0;
            PersonasListasDePrecios_IDParameter.Value=PersonasListasDePrecios_ID;
            Parameters.Add(PersonasListasDePrecios_IDParameter);

            SqlParameter Personas_IDParameter=new SqlParameter("@Personas_ID",SqlDbType.Int);
            Personas_IDParameter.Size=0;
            Personas_IDParameter.Value=Personas_ID;
            Parameters.Add(Personas_IDParameter);

            SqlParameter ListasDePrecios_IDParameter=new SqlParameter("@ListasDePrecios_ID",SqlDbType.Int);
            ListasDePrecios_IDParameter.Size=0;
            ListasDePrecios_IDParameter.Value=ListasDePrecios_ID;
            Parameters.Add(ListasDePrecios_IDParameter);

            SqlParameter PersonasDirecciones_IDParameter=new SqlParameter("@PersonasDirecciones_ID",SqlDbType.Int);
            PersonasDirecciones_IDParameter.Size=0;
            PersonasDirecciones_IDParameter.Value=PersonasDirecciones_ID;
            Parameters.Add(PersonasDirecciones_IDParameter);

             DataSet dsResult=ExecuteStoredProcedure("[Grifo].[PRC_PersonasListasDePrecios]",ref Parameters);

            return dsResult;
        }
        /// <summary>
        /// Action
        /// </summary>
        /// <param name="living"></param>
        public override void Execute(GameLiving living)
        {
            if (CheckPreconditions(living, DEAD | SITTING | MEZZED | STUNNED)) return;

            GamePlayer player = living as GamePlayer;
            if (player != null)
            {
                ArrayList targets = new ArrayList();
                if (player.Group == null)
                    targets.Add(player);
                else
                {
                    foreach (GamePlayer grpplayer in player.Group.GetPlayersInTheGroup())
                    {
                        if (player.IsWithinRadius(grpplayer, SpellRadius) && grpplayer.IsAlive)
                            targets.Add(grpplayer);
                    }
                }
                foreach (GamePlayer target in targets)
                {
                    //send spelleffect
                    if (!target.IsAlive) continue;
                    ValhallasBlessingEffect ValhallasBlessing = target.EffectList.GetOfType<ValhallasBlessingEffect>();
                    if (ValhallasBlessing != null)
                        ValhallasBlessing.Cancel(false);
                    new ValhallasBlessingEffect().Start(target);
                }
            }
            DisableSkill(living);
        }
 public IList aListOfPoint()
 {
     IList list = new ArrayList();
     list.Add(new System.Drawing.Point(0,0));
     list.Add(new System.Drawing.Point(5,5));
     return list;
 }
        public Listener( int port )
        {
            m_ThisPort = port;
            m_Disposed = false;
            m_Accepted = new Queue();
            m_OnAccept = new AsyncCallback( OnAccept );

            m_Listener = Bind( IPAddress.Any, port );

            try
            {
                IPHostEntry iphe = Dns.Resolve( Dns.GetHostName() );

                ArrayList list = new ArrayList();
                list.Add( IPAddress.Loopback );

                Console.WriteLine( "Address: {0}:{1}", IPAddress.Loopback, port );

                IPAddress[] ips = iphe.AddressList;

                for ( int i = 0; i < ips.Length; ++i )
                {
                    if ( !list.Contains( ips[i] ) )
                    {
                        list.Add( ips[i] );

                        Console.WriteLine( "Address: {0}:{1}", ips[i], port );
                    }
                }
            }
            catch
            {
            }
        }
Exemple #7
0
		public void DrainLife()
		{
			ArrayList list = new ArrayList();

			foreach ( Mobile m in this.GetMobilesInRange( 2 ) )
			{
				if ( m == this || !CanBeHarmful( m ) )
					continue;

				if ( m is BaseCreature && (((BaseCreature)m).Controlled || ((BaseCreature)m).Summoned || ((BaseCreature)m).Team != this.Team) )
					list.Add( m );
				else if ( m.Player )
					list.Add( m );
			}

			foreach ( Mobile m in list )
			{
				DoHarmful( m );

				m.FixedParticles( 0x374A, 10, 15, 5013, 0x496, 0, EffectLayer.Waist );
				m.PlaySound( 0x231 );

				m.SendMessage( "You feel the life drain out of you!" );

				int toDrain = Utility.RandomMinMax( 10, 40 );

				Hits += toDrain;
				m.Damage( toDrain, this );
			}
		}
        /// <summary>
        /// Gets/Sets the specified value
        /// </summary>
        public dynamic this[string key]
        {
            get
              {
            if (!Values.ContainsKey(key))
              return null;

            object result = Values[key];
            if (result is IDictionary<string, object>)
              result = new JsonDataObject(result as IDictionary<string, object>);
            else if (result is ArrayList)
            {
              ArrayList resultList = result as ArrayList;
              ArrayList dataList = new ArrayList();
              foreach (object current in resultList)
              {
            if (current is IDictionary<string, object>)
              dataList.Add(new JsonDataObject(current as IDictionary<string, object>));
            else
              dataList.Add(current);
              }

              result = dataList;
            }

            return result;
              }
              set
              {
            if (Values.ContainsKey(key))
              Values[key] = value;
            else
              Values.Add(key, value);
              }
        }
Exemple #9
0
        public AssemblerMethod(Method method, AssemblerLine[] lines)
        {
            this.method = method;
            this.lines = lines;
            addresses = new ArrayList ();

            ArrayList contents = new ArrayList ();
            foreach (AssemblerLine line in lines) {
                if (line.Label != null) {
                    if (end_row > 0) {
                        contents.Add ("");
                        end_row++;
                    } else
                        start_row++;
                    contents.Add (String.Format ("{0}:", line.Label));
                    end_row++;
                }

                addresses.Add (new LineEntry (line.Address, 0, ++end_row));
                contents.Add (String.Format ("  {0:x}   {1}", line.Address, line.Text));
            }

            string[] text = new string [contents.Count];
            contents.CopyTo (text);

            buffer = new SourceBuffer (method.Name, text);
        }
        public bool UpdateTjcy(ActionEnum action, Xm_Ysxx ysxx, List<Item_File> fileInfos)
        {
            ArrayList sqls = new ArrayList();
            string tmpSql;

            switch (action)
            {
                case ActionEnum.Insert:
                    sqls.Add(SqlBuilder.BuildInsertSql(ysxx));
                    break;
                case ActionEnum.Update:
                    sqls.Add(SqlBuilder.BuildUpdateSql(ysxx));
                    break;
            }

            //清空项目所有的文件。
            tmpSql = "delete from item_file where itemcode = '{0}' and nodeid = '{1}' and filecode not in ('24','25','26')";
            tmpSql = string.Format(tmpSql, ysxx.ITEMCODE, (int)WorkFlowNode.JunGong);
            sqls.Add(tmpSql);

            //插入基本信息的文件。
            foreach (Item_File fileInfo in fileInfos)
            {
                sqls.Add(SqlBuilder.BuildInsertSql(fileInfo));
            }

            return OracleHelper.ExecuteCommand(sqls);
        }
        public DataTable GetByCriteria(IEntityBase value)
        {
            EClienteBandeja objE = (EClienteBandeja)value;

            try
            {

                ArrayList arrPrm = new ArrayList();
                arrPrm.Add(DataHelper.CreateParameter("@pidEmpresa", SqlDbType.Char, 3, objE.IdEmpresa));
                arrPrm.Add(DataHelper.CreateParameter("@pidCliente", SqlDbType.Char, 7, objE.IdCliente));
                arrPrm.Add(DataHelper.CreateParameter("@pnuNif", SqlDbType.VarChar, 20, objE.NuNif));
                arrPrm.Add(DataHelper.CreateParameter("@pdsRazSocial", SqlDbType.VarChar, 150, objE.DsRazSocial));

                DataTable dt = this.ExecuteDatatable("PD_Clientes_qry01", arrPrm);

                return dt;

            }
            catch (Exception ex)
            {

                ServerObjectException objEx = (ServerObjectException)this.GetException(MethodBase.GetCurrentMethod(), ex);
                throw objEx;

            }
        }
        static void Main(string[] args)
        {
            ArrayList arrayList = new ArrayList();
            arrayList.Add("agnaldo");
            arrayList.Add(1);
            arrayList.Add(10.1205);

            Console.WriteLine(arrayList.Count);

            foreach (var item in arrayList)
                Console.WriteLine(item);

            Console.WriteLine();

            List<int> list = new List<int>();
            list.Add(1);
            list.Add(11);
            list.Add(11);
            list.Add(11);
            list.Add(11);
            list.Add(111);
            //list.Add(11.11);

            Console.WriteLine(list.Count);

            foreach (var item in list)
                Console.WriteLine(item);

            Console.ReadKey();
        }
        public ArrayList GetDataByDealer(int id)
        {
            SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=egas;Integrated Security=True;Pooling=False");
            SqlDataAdapter da = new SqlDataAdapter("select * from customer", con);
            DataSet ds = new DataSet();
            da.Fill(ds, "customer");

            ArrayList arr = new ArrayList();

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if ((int.Parse(dr[10].ToString()) != id)||(dr[13].ToString() == "PENDING" ))
                {
                    dr.Delete();
                    continue; 
                }
            }

            arr.Add(da);
            arr.Add(ds);
            return arr;



        }
        public DataTable GetByCriteria(IEntityBase value)
        {
            EConcepRemu objE = (EConcepRemu)value;

            try
            {

                ArrayList arrPrm = new ArrayList();

                arrPrm.Add(DataHelper.CreateParameter("@pidEmpresa", SqlDbType.Char, 3, objE.IdEmpresa));
                arrPrm.Add(DataHelper.CreateParameter("@pidConRemu", SqlDbType.Char, 3, objE.IdConRemu));
                arrPrm.Add(DataHelper.CreateParameter("@pdsConRemu", SqlDbType.VarChar, 50, objE.DsConRemu));
                arrPrm.Add(DataHelper.CreateParameter("@pidTipConcep", SqlDbType.Char, 3, objE.IdTipConcep));
                arrPrm.Add(DataHelper.CreateParameter("@pstCtaCte", SqlDbType.Char, 1, objE.StCtaCte));

                DataTable dt = this.ExecuteDatatable("RH_ConcepRemu_qry01", arrPrm);

                return dt;

            }
            catch (Exception ex)
            {

                ServerObjectException objEx = (ServerObjectException)this.GetException(MethodBase.GetCurrentMethod(), ex);
                throw objEx;

            }
        }
        public string GenNewCode(IEntityBase value)
        {
            ETablaCorre objE = (ETablaCorre)value;

             try
             {
            ArrayList arrPrm = new ArrayList();

            arrPrm.Add(DataHelper.CreateParameter("@pidPeriodo", SqlDbType.Char, 4, objE.IdPeriodo));
            arrPrm.Add(DataHelper.CreateParameter("@pidEmpresa", SqlDbType.Char, 3, objE.IdEmpresa));
            arrPrm.Add(DataHelper.CreateParameter("@pidTabla", SqlDbType.VarChar, 25, objE.IdTabla));

            DataTable dt = this.ExecuteDatatable("SY_TablaCorre_mnt10", arrPrm);

            int intCode = 0;
            string strFmt = "";

            foreach (DataRow dr in dt.Rows)
            {
               intCode = Convert.ToInt32(dr[0]);
               strFmt = dr[1].ToString();
            }

            return intCode.ToString(strFmt);

             }
             catch (Exception ex)
             {
            ServerObjectException objEx = (ServerObjectException)this.GetException(MethodBase.GetCurrentMethod(), ex);
            throw objEx;

             }
        }
        public int Delete(IEntityBase value)
        {
            ETablaCorre objE = (ETablaCorre)value;

             try
             {

            ArrayList arrPrm = new ArrayList();

            arrPrm.Add(DataHelper.CreateParameter("@pidPeriodo", SqlDbType.Char, 4, objE.IdPeriodo));
            arrPrm.Add(DataHelper.CreateParameter("@pidEmpresa", SqlDbType.Char, 3, objE.IdEmpresa));
            arrPrm.Add(DataHelper.CreateParameter("@pidTabla", SqlDbType.VarChar, 10, objE.IdTabla));

            int intRes = this.ExecuteNonQuery("SY_TablaCorre_mnt03", arrPrm);

            return intRes;

             }
             catch (Exception ex)
             {

            ServerObjectException objEx = (ServerObjectException)this.GetException(MethodBase.GetCurrentMethod(), ex);
            throw objEx;

             }
        }
        public void Call()
        {
            AbstractMachineState state = new AbstractMachineState(new AMFactory());
            ArrayList prog = new ArrayList();
            prog.Add(new PutConstantInstruction());
            prog.Add(new HaltInstruction());

            state.Initialize(prog);

            AMProgram program = (AMProgram)state.Program;

            ProgramClause clause = new ProgramClause("male", 2);

            program.AddLabel("male/2", clause);

            CallInstruction i = new CallInstruction();

            object[] args = { "male", "2" };

            i.Process(args);

            i.Execute(state);
            Assert.AreEqual("call", i.Name());
            Assert.AreEqual(2, i.NumberOfArguments());
            Assert.AreSame(clause, program.P);
            Assert.AreEqual("halt", program.CP.Instruction.Name());
        }
        public DataSet PRC_DocumentosCabeceraPersonasDirecciones()
        {
            ArrayList Parameters=new ArrayList(0);

            SqlParameter MODOParameter=new SqlParameter("@MODO",SqlDbType.Int);
            MODOParameter.Size=0;
            MODOParameter.Value=MODO;
            Parameters.Add(MODOParameter);

            SqlParameter DocumentosCabeceraPersonasDirecciones_IDParameter=new SqlParameter("@DocumentosCabeceraPersonasDirecciones_ID",SqlDbType.Int);
            DocumentosCabeceraPersonasDirecciones_IDParameter.Size=0;
            DocumentosCabeceraPersonasDirecciones_IDParameter.Value=DocumentosCabeceraPersonasDirecciones_ID;
            Parameters.Add(DocumentosCabeceraPersonasDirecciones_IDParameter);

            SqlParameter FechaParameter=new SqlParameter("@Fecha",SqlDbType.DateTime);
            FechaParameter.Size=0;
            FechaParameter.Value=Fecha;
            Parameters.Add(FechaParameter);

            SqlParameter DocumentosCabecera_IDParameter=new SqlParameter("@DocumentosCabecera_ID",SqlDbType.Int);
            DocumentosCabecera_IDParameter.Size=0;
            DocumentosCabecera_IDParameter.Value=DocumentosCabecera_ID;
            Parameters.Add(DocumentosCabecera_IDParameter);

            SqlParameter PersonasDirecciones_IDParameter=new SqlParameter("@PersonasDirecciones_ID",SqlDbType.Int);
            PersonasDirecciones_IDParameter.Size=0;
            PersonasDirecciones_IDParameter.Value=PersonasDirecciones_ID;
            Parameters.Add(PersonasDirecciones_IDParameter);

             DataSet dsResult=ExecuteStoredProcedure("[Grifo].[PRC_DocumentosCabeceraPersonasDirecciones]",ref Parameters);

            return dsResult;
        }
		public void MaxSize()
		{
			IKernel kernel = new DefaultKernel();
			kernel.AddComponent("a", typeof(PoolableComponent1));

			ArrayList instances = new ArrayList();

			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);
			instances.Add(kernel["a"] as PoolableComponent1);

			PoolableComponent1 other1 = kernel["a"] as PoolableComponent1;

			Assert.IsNotNull(other1);
			Assert.IsTrue(!instances.Contains(other1));

			foreach(object inst in instances)
			{
				kernel.ReleaseComponent(inst);
			}

			kernel.ReleaseComponent(other1);

			PoolableComponent1 other2 = kernel["a"] as PoolableComponent1;
			Assert.IsNotNull(other2);
			Assert.IsTrue(other1 != other2);
			Assert.IsTrue(instances.Contains(other2));

			kernel.ReleaseComponent(other2);
		}
        /// <summary>
        /// Crea Horas Para Subsidio
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int CrearHorasSubsidio(IEntityBase value)
        {
            EProcPlaCalc objE = (EProcPlaCalc)value;

              try
              {

              ArrayList arrPrm = new ArrayList();

              arrPrm.Add(DataHelper.CreateParameter("@pidPeriodo", SqlDbType.Char, 4, objE.IdPeriodo));
              arrPrm.Add(DataHelper.CreateParameter("@pidEmpresa", SqlDbType.Char, 3, objE.IdEmpresa));
              arrPrm.Add(DataHelper.CreateParameter("@pidPlanilla", SqlDbType.Char, 3, objE.IdPlanilla));
              arrPrm.Add(DataHelper.CreateParameter("@pidForPago", SqlDbType.Char, 3, objE.IdForPago));
              arrPrm.Add(DataHelper.CreateParameter("@pnuProcAnual", SqlDbType.SmallInt, objE.NuProcAnual));

              int intRes = this.ExecuteNonQuery("RH_ProcPlaCalc_ope08", arrPrm);

              return intRes;

              }
              catch (Exception ex)
              {

              ServerObjectException objEx = (ServerObjectException)this.GetException(MethodBase.GetCurrentMethod(), ex);
              throw objEx;

              }
        }
        public DataTable GetByCriteria(IEntityBase value)
        {
            EEmpPeriodo objE = (EEmpPeriodo) value;

            try
            {

                ArrayList arrPrm = new ArrayList();

                arrPrm.Add(DataHelper.CreateParameter("@pidEmpresa", SqlDbType.Char,3, objE.IdEmpresa));
                arrPrm.Add(DataHelper.CreateParameter("@pidPeriodo", SqlDbType.Char,4, objE.IdPeriodo));

                DataTable dt = this.ExecuteDatatable("SY_EmpPeriodo_qry01", arrPrm);

                return dt;

            }
            catch(Exception ex)
            {

                ServerObjectException objEx = (ServerObjectException) this.GetException(MethodBase.GetCurrentMethod(), ex);
                throw objEx;

            }
        }
Exemple #22
0
        public bool isPHPReady()
        {            
            if (!File.Exists(var.strPHPTemplateConfigFilePath))
            {
            	MessageBox.Show("The PHP template file, " + var.strPHPTemplateConfigFilePath + " cannot be found");
            	return false;
            }
            /*if (!File.Exists(var.strPHPTSConfigFilePath))
            {
            	MessageBox.Show("The PHP configuration file, " +  var.strPHPTSConfigFilePath + " cannot be found");
            	return false;
            }
            if (!File.Exists(var.strPHPNTSConfigFilePath))
            {
            	MessageBox.Show("The PHP configuration file, " + var.strPHPNTSConfigFilePath + " cannot be found");
            	return false;
            }*/
        
            // Thread-safe PHP config
            ArrayList alReplace = new ArrayList();
            alReplace.Add(new string[]{";%INCLUDE_PATH%", "include_path=\".;"+var.strPHPTSFolderPath+"\\pear\""});
            alReplace.Add(new string[]{"%EXTDIR%", Path.Combine(var.strPHPTSFolderPath, "ext")});
			File.WriteAllText(var.strPHPTSConfigFilePath, var.replaceText(File.ReadAllText(var.strPHPTemplateConfigFilePath),alReplace));
			
			// Non thread-safe PHP config
			alReplace.Clear();
			alReplace.Add(new string[]{";%INCLUDE_PATH%", "include_path=\".;"+var.strPHPNTSFolderPath+"\\pear\""});
			alReplace.Add(new string[]{"%EXTDIR%", Path.Combine(var.strPHPNTSFolderPath, "ext")});
			File.WriteAllText(var.strPHPNTSConfigFilePath, var.replaceText(File.ReadAllText(var.strPHPTemplateConfigFilePath),alReplace));
			
			Environment.SetEnvironmentVariable("PHP_FCGI_MAX_REQUESTS",var.getString("PHP","numPHPRequests"));
			
			return true;
        }
        public DataSet PRC_ProcesosCategrias()
        {
            ArrayList Parameters=new ArrayList(0);

            SqlParameter MODOParameter=new SqlParameter("@MODO",SqlDbType.Int);
            MODOParameter.Size=0;
            MODOParameter.Value=MODO;
            Parameters.Add(MODOParameter);

            SqlParameter ProcesosCategrias_IDParameter=new SqlParameter("@ProcesosCategrias_ID",SqlDbType.Int);
            ProcesosCategrias_IDParameter.Size=0;
            ProcesosCategrias_IDParameter.Value=ProcesosCategrias_ID;
            Parameters.Add(ProcesosCategrias_IDParameter);

            SqlParameter Procesos_IDParameter=new SqlParameter("@Procesos_ID",SqlDbType.Int);
            Procesos_IDParameter.Size=0;
            Procesos_IDParameter.Value=Procesos_ID;
            Parameters.Add(Procesos_IDParameter);

            SqlParameter Categorias_IDParameter=new SqlParameter("@Categorias_ID",SqlDbType.Int);
            Categorias_IDParameter.Size=0;
            Categorias_IDParameter.Value=Categorias_ID;
            Parameters.Add(Categorias_IDParameter);

             DataSet dsResult=ExecuteStoredProcedure("[Grifo].[PRC_ProcesosCategrias]",ref Parameters);

            return dsResult;
        }
        public DataTable GetByCriteria(IEntityBase value)
        {
            EPrestaCuota objE = (EPrestaCuota)value;

             try
             {

            ArrayList arrPrm = new ArrayList();

            arrPrm.Add(DataHelper.CreateParameter("@pidEmpresa", SqlDbType.Char, 3, objE.IdEmpresa));
            arrPrm.Add(DataHelper.CreateParameter("@pidPersonal", SqlDbType.Char, 7, objE.IdPersonal));
            arrPrm.Add(DataHelper.CreateParameter("@pidPrestamo", SqlDbType.Char, 4, objE.IdPrestamo));
            arrPrm.Add(DataHelper.CreateParameter("@pnuCuota", SqlDbType.SmallInt, objE.NuCuota));

            DataTable dt = this.ExecuteDatatable("RH_PrestaCuota_qry01", arrPrm);

            return dt;

             }
             catch (Exception ex)
             {

            ServerObjectException objEx = (ServerObjectException)this.GetException(MethodBase.GetCurrentMethod(), ex);
            throw objEx;

             }
        }
		public static string[] Split( string src, char delimiter, params char[] quotedelims )
		{
			ArrayList		strings = new ArrayList();
			StringBuilder	sb = new StringBuilder();
			ArrayList		ar = new ArrayList(quotedelims);
			char			quote_open = Char.MinValue;

			foreach (char c in src) 
			{
				if (c == delimiter && quote_open == Char.MinValue) 
				{
					strings.Add( sb.ToString() );
					sb.Remove( 0, sb.Length );
				}
					
				else if (ar.Contains(c)) 
				{
					if (quote_open == Char.MinValue)
						quote_open = c;
					else if (quote_open == c)
						quote_open = Char.MinValue;
					sb.Append(c);
				}
				else
					sb.Append( c );
			}

			if (sb.Length > 0)
				strings.Add( sb.ToString());

			return (string[])strings.ToArray(typeof(string));
		}
Exemple #26
0
        static void Main(string[] args)
        {
            IList list1 = new ArrayList();
            list1.Add("Hello, ");
            list1.Add("my ");
            list1.Add("dear ");
            list1.Add("old ");
            list1.Add("friend! ");

            IList list2 = new ArrayList();
            list2.Add("my ");
            list2.Add("dear ");
            list2.Add("old ");

            foreach (var value in list2)
            {
                while (list1.Contains(value))
                {
                    list1.Remove(value);
                }
            }

            foreach (var v in list1)
            {
                Console.Write(v);
            }
        }
Exemple #27
0
        public DataSet PRC_ArticulosMarcas()
        {
            ArrayList Parameters=new ArrayList(0);

            SqlParameter MODOParameter=new SqlParameter("@MODO",SqlDbType.Int);
            MODOParameter.Size=0;
            MODOParameter.Value=MODO;
            Parameters.Add(MODOParameter);

            SqlParameter ArticulosMarcas_IDParameter=new SqlParameter("@ArticulosMarcas_ID",SqlDbType.Int);
            ArticulosMarcas_IDParameter.Size=0;
            ArticulosMarcas_IDParameter.Value=ArticulosMarcas_ID;
            Parameters.Add(ArticulosMarcas_IDParameter);

            SqlParameter Articulos_IDParameter=new SqlParameter("@Articulos_ID",SqlDbType.Int);
            Articulos_IDParameter.Size=0;
            Articulos_IDParameter.Value=Articulos_ID;
            Parameters.Add(Articulos_IDParameter);

            SqlParameter Marcas_IDParameter=new SqlParameter("@Marcas_ID",SqlDbType.Int);
            Marcas_IDParameter.Size=0;
            Marcas_IDParameter.Value=Marcas_ID;
            Parameters.Add(Marcas_IDParameter);

             DataSet dsResult=ExecuteStoredProcedure("[Grifo].[PRC_ArticulosMarcas]",ref Parameters);

            return dsResult;
        }
		//rewritten by Corillian so if it doesn't work you know who to yell at ;)
		public void HandlePacket(GameClient client, GSPacketIn packet)
		{
			byte grouped = (byte)packet.ReadByte();
			ArrayList list = new ArrayList();
			if (grouped != 0x00)
			{
				ArrayList groups = GroupMgr.ListGroupByStatus(0x00);
				if (groups != null)
				{
					foreach (Group group in groups)
						if (GameServer.ServerRules.IsAllowedToGroup(group.Leader, client.Player, true))
						{
							list.Add(group.Leader);
						}
				}
			}

			ArrayList Lfg = GroupMgr.LookingForGroupPlayers();

			if (Lfg != null)
			{
				foreach (GamePlayer player in Lfg)
				{
					if (player != client.Player && GameServer.ServerRules.IsAllowedToGroup(client.Player, player, true))
					{
						list.Add(player);
					}
				}
			}

			client.Out.SendFindGroupWindowUpdate((GamePlayer[])list.ToArray(typeof(GamePlayer)));
		}
        private static ArrayList CreateSeparatedSite(String site)
        {
            if (site == null || site.Length == 0)
            {
                throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
            }
            Contract.EndContractBlock();

            ArrayList list = new ArrayList();
            int braIndex = -1;
            int ketIndex = -1;
            braIndex = site.IndexOf('[');
            if (braIndex == 0)
                ketIndex = site.IndexOf(']', braIndex+1);

            if (ketIndex != -1)
            {
                // Found an IPv6 address. Special case that
                String ipv6Addr = site.Substring(braIndex+1, ketIndex-braIndex-1);
                list.Add(ipv6Addr);
                return list;
            }

            // Regular hostnames or IPv4 addresses
            // We dont need to do this for IPv4 addresses, but it's easier to do it anyway
            String[] separatedArray = site.Split( m_separators );
            
            for (int index = separatedArray.Length-1; index > -1; --index)
            {
                if (separatedArray[index] == null)
                {
                    throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                }
                else if (separatedArray[index].Equals( "" )) 
                {
                    if (index != separatedArray.Length-1) 
                    {
                        throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                    }
                }
                else if (separatedArray[index].Equals( "*" ))
                {
                    if (index != 0)
                    {
                        throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                    }
                    list.Add( separatedArray[index] );
                }
                else if (!AllLegalCharacters( separatedArray[index] ))
                {
                    throw new ArgumentException( Environment.GetResourceString("Argument_InvalidSite" ));
                }
                else
                {
                    list.Add( separatedArray[index] );
                }
            }
            
            return list;
        }
Exemple #30
0
        static void Main(string[] args)
        {
            //ArrayList
            ArrayList arrayList = new ArrayList();
            arrayList.Add("First item");
            arrayList.Add(5);
            arrayList.Add('c');

            foreach (var item in arrayList) {
                Console.WriteLine("Element of arrayList: {0}", item);
            }

            //HashTable
            Hashtable hashtable = new Hashtable();
            hashtable.Add(0, "Zero item");
            hashtable[1] = "First item";
            hashtable["2"] = "Second item";
            hashtable[Guid.NewGuid()] = "Third item";

            ICollection keys = hashtable.Keys;
            foreach (var key in keys)
            {
                Console.WriteLine("Key: {0}, Value: {1}", key, hashtable[key]);
            }

            //SortedList
            SortedList sl = new SortedList();

            sl.Add("007", "Ritesh Saikia");
            sl.Add("001", "Zara Ali");
            sl.Add("002", "Abida Rehman");
            sl.Add("003", "Joe Holzner");
            sl.Add("004", "Mausam Benazir Nur");
            sl.Add("006", "M. Amlan");
            sl.Add("005", "M. Arif");

            ICollection slValues = sl.Values;
            foreach (var s in slValues) {
                Console.WriteLine("SortedList value: {0}", s);
            }
             //Queue is FIFO: First in First out
            Queue que = new Queue();
            que.Enqueue("Student_1");
            que.Enqueue(5);
            que.Enqueue("Student_2");
            que.Enqueue("Student_3");

            Console.WriteLine(que.Dequeue().ToString());
            Console.WriteLine(que.Dequeue().ToString());

            // Stack is FILO: First in Last out
            Stack StackPop = new Stack();
            StackPop.Push("Student_1");
            StackPop.Push("Student_2");
            StackPop.Push("Student_3");
            Console.WriteLine(StackPop.Pop().ToString());
            Console.WriteLine(StackPop.Pop().ToString());

            Console.ReadLine();
        }
        private void buttonTSSave_Click(object sender, EventArgs e)
        {
            var res = MessageBox.Show(I18N.GetValue("Make sure you have read the help before clicking OK!"), "Warning!", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if (res != DialogResult.OK)
            {
                return;
            }
            JavaScriptSerializer js = new JavaScriptSerializer();

            //mux
            currentProfile.muxSettings["enabled"]     = checkBoxMuxEnable.Checked;
            currentProfile.muxSettings["concurrency"] = Program.strToInt(textBoxMuxCc.Text, 8);
            //proxy
            //currentProfile.proxyOutboundJson = checkBoxProxy.Checked ? textBoxOutProxyJson.Text : "";
            //streamSettings
            currentProfile.streamSettings["security"] = checkBoxTLSEnable.Checked ? "tls" : "none";
            //tls
            currentProfile.streamSettings["tlsSettings"] = new Dictionary <string, object> {
                { "serverName", textBoxTLSSn.Text },
                { "allowInsecure", checkBoxTLSAI.Checked },
            };
            currentProfile.streamSettings["kcpSettings"] = new Dictionary <string, object> {
                { "mtu", Program.strToInt(textBoxKcpMtu.Text, 1350) },
                { "tti", Program.strToInt(textBoxKcpTti.Text, 20) },
                { "uplinkCapacity", Program.strToInt(textBoxKcpUc.Text, 5) },
                { "downlinkCapacity", Program.strToInt(textBoxKcpDc.Text, 20) },
                { "congestion", comboBoxKcpCon.SelectedIndex == 1 },
                { "readBufferSize", Program.strToInt(textBoxKcpRb.Text, 1) },
                { "writeBufferSize", Program.strToInt(textBoxKcpWb.Text, 1) },
                { "header", new Dictionary <string, object> {
                      { "type", comboBoxKcpHt.SelectedItem.ToString() }
                  } }
            };
            currentProfile.streamSettings["tcpSettings"] = new Dictionary <string, object> {
                { "header", checkBoxTcpHeader.Checked ?
                  js.Deserialize <object>(textBoxTcpHeader.Text)
                    : new Dictionary <string, string> {
                      { "type", "none" }
                  } }
            };
            currentProfile.streamSettings["wsSettings"] = new Dictionary <string, object> {
                { "path", textBoxWsPath.Text },
                { "headers", js.Deserialize <object>(textBoxWsHeader.Text) }
            };
            var hosts          = textBoxHttp2Hosts.Text.Split(',');
            var hosts_filtered = new System.Collections.ArrayList();

            foreach (var h in hosts)
            {
                var h_trimed = h.Trim();
                if (h_trimed.Length > 0)
                {
                    hosts_filtered.Add(h_trimed);
                }
            }
            currentProfile.streamSettings["httpSettings"] = new Dictionary <string, object> {
                { "host", hosts_filtered },
                { "path", textBoxHttp2Path.Text.Trim() }
            };
            this.Close();
        }
    protected void EditFullDayBookings()
    {
        DateTime?    old_date = UrlEditFullDay_OldDate;
        DateTime?    new_date = UrlEditFullDay_NewDate;
        Organisation old_org  = UrlEditFullDay_OldOrg;
        Organisation new_org  = UrlEditFullDay_NewOrg;
        Staff        old_prov = UrlEditFullDay_OldProvider;
        Staff        new_prov = UrlEditFullDay_NewProvider;

        if (old_date == null)
        {
            throw new Exception("Invalid url field editfullday_old_date");
        }
        if (new_date == null)
        {
            throw new Exception("Invalid url field editfullday_new_date");
        }
        if (old_org == null)
        {
            throw new Exception("Invalid url field editfullday_old_org");
        }
        if (new_org == null)
        {
            throw new Exception("Invalid url field editfullday_new_org");
        }
        if (old_prov == null)
        {
            throw new Exception("Invalid url field editfullday_old_provider");
        }
        if (new_prov == null)
        {
            throw new Exception("Invalid url field editfullday_new_provider");
        }


        // get all bookings from that day/staff/org
        // check each for clash

        bool hasClash = false;

        System.Collections.ArrayList clashes = new System.Collections.ArrayList();
        Booking[] daysBookingList            = BookingDB.GetBetween(old_date.Value, old_date.Value.AddDays(1), new Staff[] { old_prov }, new Organisation[] { old_org }, null, null, false, "0", false);

        // remove any 34 types not for this org
        System.Collections.ArrayList tmp = new System.Collections.ArrayList();
        foreach (Booking booking in daysBookingList)
        {
            if (booking.BookingTypeID != 34 || (booking.Organisation.OrganisationID == old_org.OrganisationID && booking.Provider.StaffID == old_prov.StaffID))
            {
                tmp.Add(booking);
            }
        }
        daysBookingList = (Booking[])tmp.ToArray(typeof(Booking));

        foreach (Booking booking in daysBookingList)
        {
            DateTime newDateStart = new_date.Value.AddHours(booking.DateStart.Hour).AddMinutes(booking.DateStart.Minute).AddSeconds(booking.DateStart.Second);
            DateTime newDateEnd   = new_date.Value.AddHours(booking.DateEnd.Hour).AddMinutes(booking.DateEnd.Minute).AddSeconds(booking.DateEnd.Second);

            Booking[] bookings = BookingDB.GetToCheckOverlap_OneTime(newDateStart, newDateEnd, new_prov, null, true, true, true, new Booking[] { booking });

            // remove any non 34 types (unavailabilities) for other orgs
            tmp = new System.Collections.ArrayList();
            foreach (Booking bk in bookings)
            {
                if (bk.Organisation.OrganisationID == old_org.OrganisationID || bk.BookingTypeID == 34)
                {
                    tmp.Add(bk);
                }
            }
            bookings = (Booking[])tmp.ToArray(typeof(Booking));

            if (Booking.HasOverlap(bookings, newDateStart, newDateEnd, booking))
            {
                hasClash = true;
                clashes.Add(booking.DateStart.ToString("yyyy-MM-dd HH:mm") + (booking.Patient == null ? "" : " " + booking.Patient.Person.FullnameWithoutMiddlename));
                //break;
            }
        }

        if (hasClash)
        {
            string clashesString = string.Empty;
            foreach (string s in clashes)
            {
                clashesString += (clashesString.Length == 0 ? "" : "\r\n") + s;
            }
            throw new CustomMessageException("There are clashes that need to be moved first:\r\n\r\nThese are unable to be moved:\r\n" + clashesString);
        }

        foreach (Booking booking in daysBookingList)
        {
            if (booking.BookingTypeID != 34)
            {
                continue;
            }

            DateTime newDateStart = new_date.Value.AddHours(booking.DateStart.Hour).AddMinutes(booking.DateStart.Minute).AddSeconds(booking.DateStart.Second);
            DateTime newDateEnd   = new_date.Value.AddHours(booking.DateEnd.Hour).AddMinutes(booking.DateEnd.Minute).AddSeconds(booking.DateEnd.Second);

            int bookingChangeHistoryReason = 276; // 276 = Admininstration reschedule needs
            BookingChangeHistoryDB.Insert(booking.BookingID, GetStaffID(), bookingChangeHistoryReason, booking.DateStart);
            BookingDB.Update(booking.BookingID, newDateStart, newDateEnd, new_org.OrganisationID, new_prov.StaffID, booking.Patient == null ? -1 : booking.Patient.PatientID, booking.Offering == null ? -1 : booking.Offering.OfferingID,
                             booking.BookingTypeID, booking.BookingStatus.ID, -1, booking.AddedBy.StaffID, booking.BookingConfirmedByType == null ? -1 : booking.BookingConfirmedByType.ID, booking.ConfirmedBy == null ? -1 : booking.ConfirmedBy.StaffID, booking.DateConfirmed,
                             booking.DeletedBy == null ? -1 : booking.DeletedBy.StaffID, booking.DateDeleted,
                             booking.CancelledBy == null ? -1 : booking.CancelledBy.StaffID, booking.DateCancelled,
                             booking.IsPatientMissedAppt, booking.IsProviderMissedAppt, booking.IsEmergency, booking.IsRecurring, booking.RecurringDayOfWeek, booking.RecurringStartTime, booking.RecurringEndTime);
        }
    }
    public static string MiCalculo(double inversion, double[] FNE, int[] Anio, double VdS, double TMAR, int Select, int n)
    {
        int    negativos, Periodo = n;
        double num;

        System.Collections.ArrayList ListaFinal = new System.Collections.ArrayList();
        System.Collections.ArrayList ResultadoVPNArray = new System.Collections.ArrayList();
        System.Collections.ArrayList ResultadoVAN = new System.Collections.ArrayList();
        System.Collections.ArrayList ResultadoTIR = new System.Collections.ArrayList();
        System.Collections.ArrayList ListaX = new System.Collections.ArrayList();
        System.Collections.ArrayList ListaY = new System.Collections.ArrayList();
        System.Collections.ArrayList PeriodoSelect = new System.Collections.ArrayList();
        double ResultadoVPN, RCalcuTIR;

        double [] valores = new double[Anio.Length];
        for (int a = 1; a <= Anio.Length; a++)
        {
            for (int b = 0; b < Anio.Length; b++)
            {
                if (a == Anio[b])
                {
                    valores[a - 1] = FNE[b];
                    break;
                }
            }
        }
        FNE = valores;
        /* System.Diagnostics.Debug.WriteLine(PeriodoSelect);   Linea de codigo para ver en consola las cosas */
        ResultadoVPN = CalcularVPN(inversion, FNE, VdS, TMAR / 100, n);
        ResultadoVPNArray.Add(ResultadoVPN);
        ListaFinal.Add(ResultadoVPNArray);
        ResultadoVAN.Add("$" + ResultadoVPN.ToString("0,0.0000"));
        List <double> resultados = CalcularTIR(inversion, FNE, VdS, n);

        RCalcuTIR = resultados[0];
        ResultadoTIR.Add((RCalcuTIR).ToString("0,0.00000000") + " %");
        ListaFinal.Add(ResultadoVAN);
        ListaFinal.Add(ResultadoTIR);

        TMAR = RCalcuTIR / 20;
        double TMAR2 = Math.Round(RCalcuTIR, 4);
        int    contador = 0;
        int    pos = 0;

        do
        {
            ListaX.Add(Math.Round(TMAR, 4));
            ListaY.Add(Math.Round(CalcularVPN(inversion, FNE, VdS, TMAR / 100, n), 4));
            negativos = 0;

            foreach (var item in ListaY)
            {
                num = Convert.ToDouble(item);
                if (num < 0)
                {
                    negativos++;
                }
            }
            if (TMAR2 == Math.Round(TMAR, 4))
            {
                pos = contador;
            }
            TMAR = TMAR + (RCalcuTIR / 20); // Cantidad de saltos de los puntos en el eje X
            contador++;
        } while (negativos < 5);            // Solo 5 numeros negativos despues del cruce con 0 en el eje x

        ListaFinal.Add(ListaX);
        ListaFinal.Add(ListaY);
        if (1 == Select)
        {
            PeriodoSelect.Add("Mes");
        }
        else
        {
            PeriodoSelect.Add("Año");
        }
        ListaFinal.Add(PeriodoSelect);
        ListaFinal.Add(pos);
        ListaFinal.Add(RCalcuTIR);
        if (resultados[1] == 0)
        {
            ListaFinal.Add("$ " + resultados[1]);
        }
        else
        {
            string formattedString = "$" + String.Format("{0:N35}", resultados[1]);
            ListaFinal.Add(formattedString);
        }
        String json = JsonConvert.SerializeObject(ListaFinal);

        return(json);
    }
Exemple #34
0
    /// <summary>
    /// Creates a <see cref="CommandLineArguments"/> object to parse
    /// command lines.
    /// </summary>
    /// <param name="args">The command line to parse.</param>
    internal CommandLineArguments(string[] args)
    {
        Regex splitter = new Regex(@"^-{1,2}|^/|=|:",
                                   RegexOptions.IgnoreCase | RegexOptions.Compiled);
        Regex remover = new Regex(@"^['""]?(.*?)['""]?$",
                                  RegexOptions.IgnoreCase | RegexOptions.Compiled);
        string parameter = null;

        string[] parts;

        // Valid parameters forms:
        // {-,/,--}param{ ,=,:}((",')value(",'))
        // Examples: -param1 value1 --param2 /param3:"Test-:-work"
        //           /param4=happy -param5 '--=nice=--'
        foreach (string str in args)
        {
            // Do we have a parameter (starting with -, /, or --)?
            if (str.StartsWith("-") || str.StartsWith("/"))
            {
                // Look for new parameters (-,/ or --) and a possible
                // enclosed value (=,:)
                parts = splitter.Split(str, 3);
                switch (parts.Length)
                {
                // Found a value (for the last parameter found
                // (space separator))
                case 1:
                    if (parameter != null)
                    {
                        if (!namedParameters.ContainsKey(parameter))
                        {
                            parts[0] =
                                remover.Replace(parts[0], "$1");
                            namedParameters.Add(
                                parameter, parts[0]);
                        }
                        parameter = null;
                    }
                    // else Error: no parameter waiting for a value
                    // (skipped)
                    break;

                // Found just a parameter
                case 2:
                    // The last parameter is still waiting. With no
                    // value, set it to true.
                    if (parameter != null)
                    {
                        if (!namedParameters.ContainsKey(parameter))
                        {
                            namedParameters.Add(parameter, "true");
                        }
                    }
                    parameter = parts[1];
                    break;

                // parameter with enclosed value
                case 3:
                    // The last parameter is still waiting. With no
                    // value, set it to true.
                    if (parameter != null)
                    {
                        if (!namedParameters.ContainsKey(parameter))
                        {
                            namedParameters.Add(parameter, "true");
                        }
                    }
                    parameter = parts[1];
                    // Remove possible enclosing characters (",')
                    if (!namedParameters.ContainsKey(parameter))
                    {
                        parts[2] = remover.Replace(parts[2], "$1");
                        namedParameters.Add(parameter, parts[2]);
                    }
                    parameter = null;
                    break;
                }
            }
            else
            {
                unnamedParameters.Add(str);
            }
        }
        // In case a parameter is still waiting
        if (parameter != null)
        {
            if (!namedParameters.ContainsKey(parameter))
            {
                namedParameters.Add(parameter, "true");
            }
        }
    }
        public static double GetEstimatedNumOfLeaveDays(DatabaseConnection dbConn, int EmpID, DateTime DateFrom, DateTime DateTo, int LeaveCodeID, out DateTime[] DateSkipArray)
        {
            System.Collections.ArrayList dateSkipArrayList = new System.Collections.ArrayList();

            EEmpPositionInfo empPos    = null;
            double           totalDays = 0;

            ELeaveType leaveType = new ELeaveType();

            leaveType.LeaveTypeIsUseWorkHourPattern = true;

            ELeaveCode leaveCode = new ELeaveCode();

            leaveCode.LeaveCodeID = LeaveCodeID;
            if (ELeaveCode.db.select(dbConn, leaveCode))
            {
                leaveType.LeaveTypeID = leaveCode.LeaveTypeID;
                ELeaveType.db.select(dbConn, leaveType);
            }
            for (DateTime currentDate = DateFrom; currentDate <= DateTo; currentDate = currentDate.AddDays(1))
            {
                //  default every date count = 1
                double dateCount = 1;
                if (EStatutoryHoliday.IsHoliday(dbConn, currentDate))
                {
                    if (!leaveType.LeaveTypeIsSkipStatutoryHolidayChecking)
                    {
                        dateCount = 0;
                    }
                }
                else if (EPublicHoliday.IsHoliday(dbConn, currentDate))
                {
                    if (!leaveType.LeaveTypeIsSkipPublicHolidayChecking)
                    {
                        dateCount = 0;
                    }
                }

                if (empPos == null)
                {
                    empPos = AppUtils.GetLastPositionInfo(dbConn, currentDate, EmpID);
                }
                else
                if (!empPos.EmpPosEffTo.Ticks.Equals(0) && empPos.EmpPosEffTo <= currentDate)
                {
                    empPos = AppUtils.GetLastPositionInfo(dbConn, currentDate, EmpID);
                }

                if (empPos != null)
                {
                    EWorkHourPattern workPattern = new EWorkHourPattern();
                    workPattern.WorkHourPatternID = empPos.WorkHourPatternID;
                    if (EWorkHourPattern.db.select(dbConn, workPattern))
                    {
                        if (leaveType.LeaveTypeIsUseWorkHourPattern)
                        {
                            dateCount = workPattern.GetDefaultDayUnit(dbConn, currentDate, leaveType.LeaveTypeIsSkipStatutoryHolidayChecking, leaveType.LeaveTypeIsSkipPublicHolidayChecking);
                        }
                    }
                }


                totalDays += dateCount;

                if (dateCount <= 0)
                {
                    dateSkipArrayList.Add(currentDate);
                }
            }

            DateSkipArray = (DateTime[])dateSkipArrayList.ToArray(typeof(DateTime));
            return(totalDays);
        }
Exemple #36
0
 /// <summary>
 /// 當查詢SQL以參數方式提供時,接著透過呼叫putQueryParameter設定各個參數值,最後再呼叫 prepareStatement(),完成查詢設定。
 /// [Nick Young@20160825]
 /// </summary>
 public void putQueryParameter(string key, string value)
 {
     QueryParameterList.Add(new String[] { key, value });
 }
    protected void CheckClashOneTimeBooking()
    {
        UserView userView = UserView.GetInstance();

        string org_id          = Request.QueryString["org"];
        string all_orgs        = Request.QueryString["all_orgs"];
        string staff_id        = Request.QueryString["staff"];
        string booking_id      = Request.QueryString["edit_booking_id"];
        string booking_type_id = Request.QueryString["booking_type_id"];

        string start_datetime = Request.QueryString["start_datetime"];
        string end_datetime   = Request.QueryString["end_datetime"];


        if (start_datetime == null || !Regex.IsMatch(start_datetime, @"^\d{4}_\d{2}_\d{2}_\d{4}$") ||
            end_datetime == null || !Regex.IsMatch(end_datetime, @"^\d{4}_\d{2}_\d{2}_\d{4}$") ||
            org_id == null || !Regex.IsMatch(org_id, @"^\-?\d+$") ||
            staff_id == null || !Regex.IsMatch(staff_id, @"^\-?\d+$") ||
            booking_id == null || !Regex.IsMatch(booking_id, @"^\-?\d+$"))
        {
            throw new CustomMessageException();
        }

        Organisation org     = OrganisationDB.GetByID(Convert.ToInt32(org_id));
        Staff        staff   = StaffDB.GetByID(Convert.ToInt32(staff_id));
        Booking      booking = booking_id == "-1" ? null : BookingDB.GetByID(Convert.ToInt32(booking_id));

        if (booking != null && booking_type_id == "-1")
        {
            booking_type_id = booking.BookingTypeID.ToString();
        }

        if ((org_id != "0" && org == null) ||
            (staff_id != "-1" && staff == null) ||
            (booking_id != "-1" && booking == null) ||
            (booking_type_id == null || (booking_type_id != "34" && booking_type_id != "340" && booking_type_id != "341" && booking_type_id != "342")))
        {
            throw new CustomMessageException();
        }

        DateTime startDateTime = ConvertStringToDateTime(start_datetime);
        DateTime endDateTime   = ConvertStringToDateTime(end_datetime);

        // if pt logged in, disallow booking over unavailabilities, otherwise allow it and ignore the check
        bool checkUnavailableDays = userView.IsPatient;

        Booking[] bookings = (all_orgs != null && all_orgs == "1") ?
                             BookingDB.GetToCheckOverlap_OneTime(startDateTime, endDateTime, staff, null, booking_type_id == "342", true, checkUnavailableDays) :
                             BookingDB.GetToCheckOverlap_OneTime(startDateTime, endDateTime, staff, org, booking_type_id == "342", true, checkUnavailableDays);

        if (bookings.Length > 0)
        {
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            for (int i = 0; i < bookings.Length; i++)
            {
                if ((bookings[i].Organisation == null || (org != null && bookings[i].Organisation.OrganisationID == org.OrganisationID)) &&
                    (bookings[i].Provider == null || bookings[i].Provider.StaffID == staff.StaffID))
                {
                    list.Add(bookings[i]);
                }
            }
            bookings = (Booking[])list.ToArray(typeof(Booking));
        }

        // for patient, disallow booking over start/end times when clinic unavailable
        if (userView.IsPatient)
        {
            if (org == null)
            {
                org = booking.Organisation;
            }
            StartEndTime startEndTime      = org.GetStartEndTime(startDateTime.DayOfWeek);
            StartEndTime startEndLunchTime = org.GetStartEndLunchTime(startDateTime.DayOfWeek);
            if ((startEndTime.StartTime < startEndTime.EndTime && startDateTime.TimeOfDay < endDateTime.TimeOfDay && !(startDateTime.TimeOfDay >= startEndTime.StartTime && endDateTime.TimeOfDay <= startEndTime.EndTime)) ||
                (startEndLunchTime.StartTime < startEndLunchTime.EndTime && startDateTime.TimeOfDay < endDateTime.TimeOfDay && Booking.TimeIntersects(startEndLunchTime.StartTime, startEndLunchTime.EndTime, startDateTime.TimeOfDay, endDateTime.TimeOfDay)))
            {
                Response.Write("1");
                return;
            }
        }


        Response.Write(Booking.HasOverlap(bookings, startDateTime, endDateTime, booking) ? "1" : "0");
    }
    protected void CheckClashFullDayBookings()
    {
        string old_edit_date        = Request.QueryString["editfullday_old_date"];
        string old_edit_org_id      = Request.QueryString["editfullday_old_org"];
        string old_edit_provider_id = Request.QueryString["editfullday_old_provider"];
        string new_edit_date        = Request.QueryString["editfullday_new_date"];
        string new_edit_org_id      = Request.QueryString["editfullday_new_org"];
        string new_edit_provider_id = Request.QueryString["editfullday_new_provider"];

        if (old_edit_date == null || !Regex.IsMatch(old_edit_date, @"^\d{4}_\d{2}_\d{2}$") ||
            new_edit_date == null || !Regex.IsMatch(new_edit_date, @"^\d{4}_\d{2}_\d{2}$") ||
            old_edit_org_id == null || !Regex.IsMatch(old_edit_org_id, @"^\d+$") ||
            new_edit_org_id == null || !Regex.IsMatch(new_edit_org_id, @"^\d+$") ||
            old_edit_provider_id == null || !Regex.IsMatch(old_edit_provider_id, @"^\d+$") ||
            new_edit_provider_id == null || !Regex.IsMatch(new_edit_provider_id, @"^\d+$"))
        {
            throw new CustomMessageException();
        }


        DateTime oldEditDateTime = ConvertStringToDateTime(old_edit_date + "_0000");
        DateTime newEditDateTime = ConvertStringToDateTime(new_edit_date + "_0000");

        Organisation oldOrg   = OrganisationDB.GetByID(Convert.ToInt32(old_edit_org_id));
        Organisation newOrg   = OrganisationDB.GetByID(Convert.ToInt32(new_edit_org_id));
        Staff        oldStaff = StaffDB.GetByID(Convert.ToInt32(old_edit_provider_id));
        Staff        newStaff = StaffDB.GetByID(Convert.ToInt32(new_edit_provider_id));

        if (oldOrg == null ||
            newOrg == null ||
            oldStaff == null ||
            newStaff == null)
        {
            throw new CustomMessageException();
        }



        // get all bookings from that day/staff/org
        // check each for clash

        bool hasClash = false;

        Booking[] daysBookingList = BookingDB.GetBetween(oldEditDateTime, oldEditDateTime.AddDays(1), new Staff[] { oldStaff }, new Organisation[] { oldOrg }, null, null, false, "0", false);

        // remove any 34 types not for this org
        System.Collections.ArrayList tmp = new System.Collections.ArrayList();
        foreach (Booking booking in daysBookingList)
        {
            if (booking.BookingTypeID != 34 || (booking.Organisation.OrganisationID == oldOrg.OrganisationID && booking.Provider.StaffID == oldStaff.StaffID))
            {
                tmp.Add(booking);
            }
        }
        daysBookingList = (Booking[])tmp.ToArray(typeof(Booking));

        foreach (Booking booking in daysBookingList)
        {
            DateTime newDateStart = newEditDateTime.AddHours(booking.DateStart.Hour).AddMinutes(booking.DateStart.Minute).AddSeconds(booking.DateStart.Second);
            DateTime newDateEnd   = newEditDateTime.AddHours(booking.DateEnd.Hour).AddMinutes(booking.DateEnd.Minute).AddSeconds(booking.DateEnd.Second);

            Booking[] bookings = BookingDB.GetToCheckOverlap_OneTime(newDateStart, newDateEnd, newStaff, null, true, true, true, new Booking[] { booking });

            // remove any non 34 types (unavailabilities) for other orgs
            tmp = new System.Collections.ArrayList();
            foreach (Booking bk in bookings)
            {
                if (bk.Organisation.OrganisationID == oldOrg.OrganisationID || bk.BookingTypeID == 34)
                {
                    tmp.Add(bk);
                }
            }
            bookings = (Booking[])tmp.ToArray(typeof(Booking));

            if (Booking.HasOverlap(bookings, newDateStart, newDateEnd, booking))
            {
                hasClash = true;
                break;
            }
        }

        Response.Write(hasClash ? "1" : "0");
    }
Exemple #39
0
        public bool OpenProject(string strProject, string strUser, string strPassword,
                                out string strErrDiag)
        {
            strErrDiag = "";
            bool bRet = false;

            try
            {
                if (state != eState.stDisc)
                {
                    CloseProject();
                }
                cb.ShowProgressOpenProject("Opening " + strProject);
                rpxProject = (ReqPro40.Project___v7)rpxApplication.OpenProject(strProject,
                                                                               ReqPro40.enumOpenProjectOptions.eOpenProjOpt_RQSFile,
                                                                               strUser,
                                                                               strPassword,
                                                                               ReqPro40.enumProjectFlags.eProjFlag_Normal,
                                                                               ReqPro40.enumRelatedProjectOptions.eRelatedProjOption_ConnectAll);
                state = eState.stConn;
                bRet  = true;

                ReqProRequirementPrx.HomePrjPrefix = rpxProject.Prefix;

                int    nCountRelPrj = rpxProject.RelatedProjectContexts.Count;
                bool   bLoadRelPrj;
                string strRelPrjPassword;
                string strRelPrjUser;

                cb.ShowProgressOpenProject("Related Projects to be opened: " + nCountRelPrj);

                ReqPro40.RelatedProjectContext rpxRelPrjCtx;
                ReqPro40.Project___v7          rpxRelPrj;

                for (int i = 0; i < nCountRelPrj; i++)
                {
                    rpxRelPrjCtx      = rpxProject.RelatedProjectContexts[i + 1, ReqPro40.enumRelatedProjectLookups.eRelProjLookup_Index];
                    bLoadRelPrj       = true;
                    strRelPrjPassword = strPassword;
                    strRelPrjUser     = strUser;
                    rpxRelPrj         = null;
                    if (!rpxRelPrjCtx.IsOpen)
                    {
                        while (bLoadRelPrj)
                        {
                            try
                            {
                                cb.ShowProgressOpenProject("Opening: " + rpxRelPrjCtx.get_Name());
                                rpxRelPrj = (ReqPro40.Project___v7)rpxRelPrjCtx.OpenProject(strRelPrjUser, strRelPrjPassword);
                                cb.ShowProgressOpenProject("Opened: " + rpxRelPrj.Name);
                            }
                            catch (System.Runtime.InteropServices.COMException e)
                            {
                                bool bPasswordError;
                                unchecked
                                {
                                    bPasswordError = (e.ErrorCode == (int)0x8004088b);
                                }
                                if (bPasswordError)
                                {
                                    bLoadRelPrj = cb.RequestCredentials(rpxRelPrjCtx.get_Name(),
                                                                        ref strRelPrjUser, out strRelPrjPassword);
                                }
                                else
                                {
                                    bLoadRelPrj = false;
                                }
                            }
                        }
                    }
                    else
                    {
                        rpxRelPrj = (ReqPro40.Project___v7)rpxRelPrjCtx.ThisProject;
                        cb.ShowProgressOpenProject("Already opened: " + rpxRelPrj.Name);
                    }

                    if (rpxRelPrj != null)
                    {
                        arpxRelProjects.Add(rpxRelPrj);
                    }
                }
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                strErrDiag = e.Message;
            }
            return(bRet);
        }
Exemple #40
0
    public static int MainImpl(string[] args)
    {
        // Load defaults from app.config.
        settings = new Settings();

        // Were any command line args specified?
        if (args.Length > 0)
        {
            // Override default settings with command line args.
            CommandLine.Parse(args, settings);
        }
        else
        {
            // Obtain arguments from UI.
            PromptForArgs dlg = new PromptForArgs(settings);

            if (dlg.ShowDialog() != DialogResult.OK)
            {
                return(1);
            }
        }

        // Validate arguments.
        if (settings.FilePattern == null ||
            settings.RegexPattern == null)
        {
            throw new ApplicationException("Please specify at least a pathspec and regex pattern.");
        }

        // Default basedir to cwd.
        if (settings.BaseDirectory == null ||
            settings.BaseDirectory == string.Empty)
        {
            settings.BaseDirectory = System.Environment.CurrentDirectory;
        }

        // Echo command line options.
        Console.Write(@"Searching directory ""{0}"", files ""{1}"", for pattern ""{2}"" (options: ", settings.BaseDirectory, settings.FilePattern, settings.RegexPattern);

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

        if (settings.RegexIgnoreCase)
        {
            optionstrings.Add("IgnoreCase");
        }
        if (settings.RegexSingleline)
        {
            optionstrings.Add("Singleline");
        }
        if (settings.RegexMimicVS)
        {
            optionstrings.Add("RegexMimicVS");
        }
        if (settings.ActiveReplace)
        {
            optionstrings.Add("ActiveReplace");
        }
        if (settings.ReplacementText != null)
        {
            optionstrings.Add(String.Format("Replacement pattern: {0}", settings.ReplacementText));
        }

        if (optionstrings.Count == 0)
        {
            optionstrings.Add("none");
        }

        Console.Write(String.Join(", ", (string[])optionstrings.ToArray(typeof(string))));
        Console.WriteLine(")");
        Console.WriteLine();

        // Reimplement VS7's helper patterns for things like C identifiers, numbers, string literals, etc.
        if (settings.RegexMimicVS)
        {
            settings.RegexPattern = settings.RegexPattern.Replace("::", "\x3A");
            settings.RegexPattern = settings.RegexPattern.Replace(":i", @"([_a-zA-Z][_a-zA-Z0-9]*)");
            settings.RegexPattern = settings.RegexPattern.Replace(":n", @"(\b[-]?[0-9]+(\.[0-9]+([Ee](\+|-)?[0-9]+)?)?\b)");
            settings.RegexPattern = settings.RegexPattern.Replace(":q", @"((@""(""""|[^""])*"")|(""(\\.|[^""\\])*""))");
        }

        // Create the regex, and populate the visitor callback with it.
        RegexOptions ro = RegexOptions.Compiled | RegexOptions.Multiline;

        if (settings.RegexIgnoreCase)
        {
            ro |= RegexOptions.IgnoreCase;
        }
        if (settings.RegexSingleline)
        {
            ro |= RegexOptions.Singleline;
        }

        FileVisitor visitor = new FileVisitor();

        visitor.UserRegex       = new Regex(settings.RegexPattern, ro);
        visitor.ActiveReplace   = settings.ActiveReplace;
        visitor.ReplacementText = settings.ReplacementText;
        visitor.BackupDirectory = settings.BackupDirectory;

        visitor.OutputWidth = settings.OutputWidth;

        // configure colours
        visitor.DefaultColor         = settings.DefaultColor;
        visitor.FileDirectoryColor   = settings.FileDirectoryColor;
        visitor.FileNameColor        = settings.FileNameColor;
        visitor.LineNumberColor      = settings.LineNumberColor;
        visitor.SurroundingTextColor = settings.SurroundingTextColor;
        visitor.MatchedTextColor     = settings.MatchedTextColor;
        visitor.ErrorColor           = settings.ErrorColor;

        visitor.SuppressError = settings.SuppressError;

        // Do the dew!
        Jitsu.IO.DirectoryTraverser.FileVisitor onFile =
            new Jitsu.IO.DirectoryTraverser.FileVisitor(visitor.VisitFile);
        Jitsu.IO.DirectoryTraverser spider =
            new Jitsu.IO.DirectoryTraverser(null, onFile, settings.FileExclusions, settings.DirectoryExclusions, settings.IgnoreHiddenFiles, settings.IgnoreHiddenDirectories);

        string directoryPattern = (settings.DontRecurse) ? "" : "*";

        spider.TraverseBreadthFirst(settings.BaseDirectory, settings.FilePattern, directoryPattern);

        // Report the results, in standard VS7 format.
        Win32.TrySetConsoleColor(settings.DefaultColor);

//		Console.WriteLine( "Total found: {0}    Matching files: {1}    Total files searched: {2}",
//			visitor.MatchesFound, visitor.FilesFound, visitor.FilesSearched);
        Console.WriteLine(
            //"Total of {0} file{1} processed. Skipped {2} file{3}. Searched {4} file{5}. {6} match{7} found in {8} file{9}.",
            "{6:#,###;;No} match{7} in {8:#,###;;zero} file{9}. " +
            "Processed {0:#,###;;none}. Skipped {2:#,###;;none}. Searched {4:#,###;;none}.",
            visitor.FilesProcessed,
            visitor.FilesProcessed == 1 ? "" : "s",
            visitor.FilesSkipped,
            visitor.FilesSkipped == 1 ? "" : "s",
            visitor.FilesSearched,
            visitor.FilesSearched == 1 ? "" : "s",
            visitor.MatchesFound,
            visitor.MatchesFound == 1 ? "" : "es",
            visitor.FilesFound,
            visitor.FilesFound == 1 ? "" : "s"
            );

        // Done.
        return(0);
    }
    public static string optimizacionFNE(double inversion, double[] FNE, double VS, int periodo, double tir, double porcentajeextraganancia)
    {
        System.Collections.ArrayList ListaFinal = new System.Collections.ArrayList();

        int           poblacionNumero = 1200;
        List <double> FNEList         = FNE.ToList();
        double        FNEMax          = FNEList.Max();
        double        FNEMin          = FNEList.Min();

        double porcentajeFNEMax = FNEMax / 100;
        double porcentajeFNEMin = FNEMin / 100;

        FNEMax = FNEMax + (porcentajeFNEMax * porcentajeextraganancia);
        FNEMin = FNEMin - (porcentajeFNEMin * porcentajeextraganancia);

        List <List <double> > poblacion2 = new List <List <double> >();
        Random random = new Random();

        while (poblacion2.Count < poblacionNumero)
        {
            List <double> poblaciontem = new List <double>();
            while (poblaciontem.Count < periodo)
            {
                double numeroAleatorio = random.NextDouble() * ((FNEMax + 1) - (FNEMin - 1)) + (FNEMin - 1);
                if (!poblaciontem.Contains(numeroAleatorio))
                {
                    poblaciontem.Add(numeroAleatorio);
                }
            }
            poblacion2.Add(poblaciontem);
        }
        int           j = 1;
        double        porcentajeconvergencia2 = 0;
        double        porcentaje2             = (((double)100) / poblacionNumero);
        List <double> ResultadosFX2;
        Random        random2b = new Random();

        do
        {
            ResultadosFX2 = fxFNE(inversion, poblacion2, VS, tir, periodo);

            List <int>            torneo1b = posTorneo(0, poblacion2.Count / 2);
            List <int>            torneo2b = posTorneo(poblacion2.Count / 2, poblacion2.Count);
            List <List <double> > padre2   = SeleccionFNE(torneo1b, torneo2b, ResultadosFX2, poblacion2, FNEMax);

            List <int> cruce1b = posTorneo(0, padre2.Count / 2);
            List <int> cruce2b = posTorneo(padre2.Count / 2, padre2.Count);

            List <List <double> > hijos_Generadosb = new List <List <double> >();

            double probCruzb = random2b.NextDouble();

            if (probCruzb < 0.9)
            {
                hijos_Generadosb = CruceTotal2(padre2, cruce1b, cruce2b, j);
            }
            else
            {
                hijos_Generadosb = padre2;
            }

            poblacion2.Clear();
            poblacion2 = padre2.Concat(hijos_Generadosb).ToList();
            poblacion2 = DesordenarLista(poblacion2);
            //List<List<double>> poblacionanalisis = new List<List<double>>(poblacion2); permite pasar en otra lista
            List <double> convergencia = medir_convergencia2(poblacion2);
            var           agrupacion   = convergencia.OrderByDescending(o => o).ToList();
            var           agrupacion2  = agrupacion.GroupBy(x => x).Select(g => new { Text = g.Key, Count = g.Count() }).ToList();
            var           valormax     = agrupacion.Max();

            foreach (var el in agrupacion2)
            {
                if (el.Text == valormax && el.Count == 1)
                {
                    double valor = Convert.ToDouble(el.Text);
                    porcentajeconvergencia2 = porcentaje2 * valor;
                }
                break;
            }
            if (porcentajeconvergencia2 < (double)99.9)
            {
                j = j + 1;
            }
        } while (porcentajeconvergencia2 < (double)99.9);

        ListaFinal.Add(poblacion2[0]);
        ListaFinal.Add(FNEList);
        ListaFinal.Add(ResultadosFX2[0]);
        ListaFinal.Add(tir);

        String json = JsonConvert.SerializeObject(ListaFinal);

        Thread.Sleep(450);
        return(json);
    }
    public static string CreacionTabla(decimal inversion, decimal[] Costos, decimal[] Ingresos, decimal[] FNE, int[] AnioV, decimal VdS, decimal TMAR, int Select, int n)
    {
        System.Collections.ArrayList ListaFinal  = new System.Collections.ArrayList();
        System.Collections.ArrayList PeridoRec   = new System.Collections.ArrayList();
        System.Collections.ArrayList PeridoRecP2 = new System.Collections.ArrayList();
        System.Collections.ArrayList BenCosto    = new System.Collections.ArrayList();

        decimal[] valores  = new decimal[AnioV.Length];
        decimal[] valores1 = new decimal[AnioV.Length];
        decimal[] valores2 = new decimal[AnioV.Length];

        for (int a = 1; a <= AnioV.Length; a++)
        {
            for (int b = 0; b < AnioV.Length; b++)
            {
                if (a == AnioV[b])
                {
                    valores[a - 1]  = Costos[b];
                    valores1[a - 1] = Ingresos[b];
                    valores2[a - 1] = FNE[b];
                    break;
                }
            }
        }
        Costos   = valores;
        Ingresos = valores1;
        FNE      = valores2;

        String PeriodoSelect;
        String PeridoRec2 = "";
        String PeridoRec3 = "";

        if (1 == Select)
        {
            PeriodoSelect = "Mes";
        }
        else
        {
            PeriodoSelect = "Año";
        }

        TMAR = TMAR / 100;
        int Periodo = n;

        String[,] ArregloDatos = new String[Periodo + 1, 8];
        ArregloDatos[0, 3]     = ArregloDatos[0, 4] = ArregloDatos[0, 5] = "";
        ArregloDatos[0, 2]     = "-" + inversion.ToString();
        ArregloDatos[0, 7]     = "-" + inversion.ToString();
        for (int j = 0; j <= Periodo; j++)
        {
            ArregloDatos[j, 0] = Convert.ToString(j + 1);
        }
        for (int j = 0; j <= Periodo; j++)
        {
            ArregloDatos[j, 1] = PeriodoSelect + " " + Convert.ToString(j);
        }
        for (int j = 1; j <= Periodo; j++)
        {
            ArregloDatos[j, 2] = Convert.ToString(Costos[j - 1]);
        }
        for (int j = 1; j <= Periodo; j++)
        {
            ArregloDatos[j, 3] = Convert.ToString(Ingresos[j - 1]);
        }
        for (int j = 1; j <= Periodo; j++)
        {
            ArregloDatos[j, 4] = FNE[j - 1].ToString();
        }
        for (int j = 1; j <= Periodo; j++)
        {
            decimal IngresoActual = (Convert.ToDecimal(ArregloDatos[j, 3])) / Convert.ToDecimal(Math.Pow((double)(1 + TMAR), j));
            ArregloDatos[j, 5] = Convert.ToString(Math.Round(IngresoActual, 3));
        }

        /*Calculo de periodo de recuperacion en funcion del ingreso actualizado en tabla*/
        for (int i = 1; i <= Periodo; i++)
        {
            decimal x = Convert.ToDecimal(ArregloDatos[i - 1, 7]);
            decimal ingresactualiza = Convert.ToDecimal(ArregloDatos[i, 5]);
            ArregloDatos[i, 7] = Convert.ToString(x + ingresactualiza);
        }
        /*Calculo de periodo de recuperacion en funcion del ingreso actualizado en tabla*/

        /*Calculo de periodo de recuperacion en tabla*/
        ArregloDatos[0, 6] = ArregloDatos[0, 2];
        for (int i = 1; i <= Periodo; i++)
        {
            decimal x         = Convert.ToDecimal(ArregloDatos[i - 1, 6]);
            decimal Flujoneto = Convert.ToDecimal(ArregloDatos[i, 4]);
            ArregloDatos[i, 6] = Convert.ToString(x + Flujoneto);
        }
        ListaFinal.Add(ArregloDatos);
        /*Calculo de periodo de recuperacion en tabla*/

        /*Calculo de periodo de recuperacion*/
        decimal P = inversion;

        for (int i = 1; i <= Periodo; i++)
        {
            decimal x1 = Convert.ToDecimal(ArregloDatos[i, 6]);
            if (x1 >= 0)
            {
                decimal x2 = Convert.ToDecimal(ArregloDatos[i - 1, 6]);
                if (x2 < 0)
                {
                    decimal Anio = Convert.ToDecimal(ArregloDatos[i - 1, 0]);
                    if (PeriodoSelect == "Mes")
                    {
                        decimal T1 = Math.Round(((P / ((x2 * -1M) + x1)) + (Anio - 1)), 3);

                        if (T1 > 1)
                        {
                            double valorConDecimal = (double)T1;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec2 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + "es con " + decimales + " dia(s)";
                        }
                        else
                        {
                            double valorConDecimal = (double)T1;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec2 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + " " + decimales + " dia(s)";
                        }
                    }
                    else
                    {
                        decimal T2 = Math.Round(((P / ((x2 * -1) + x1)) + (Anio - 1)), 3);
                        if (T2 > 1)
                        {
                            double valorConDecimal = (double)T2;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec2 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + "s con " + decimales + " mes(es)";
                        }
                        else
                        {
                            double valorConDecimal = (double)T2;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec2 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + " " + decimales + " mes(es)";
                        }
                    }
                    break;
                }
            }
            else
            {
                PeridoRec2 = "No es posible calcular";
            }
        }

        PeridoRec.Add(PeridoRec2);
        ListaFinal.Add(PeridoRec);

        for (int i = 1; i <= Periodo; i++)
        {
            decimal x1 = Convert.ToDecimal(ArregloDatos[i, 7]);
            if (x1 >= 0)
            {
                decimal x2 = Convert.ToDecimal(ArregloDatos[i - 1, 7]);
                if (x2 < 0)
                {
                    decimal Anio = Convert.ToDecimal(ArregloDatos[i - 1, 0]);
                    if (PeriodoSelect == "Mes")
                    {
                        decimal T1 = Math.Round(((P / ((x2 * -1M) + x1)) + (Anio - 1)), 3);

                        if (T1 > 1)
                        {
                            double valorConDecimal = (double)T1;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec3 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + "es con " + decimales + " dia(s)";
                        }
                        else
                        {
                            double valorConDecimal = (double)T1;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec3 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + " " + decimales + " dia(s)";
                        }
                    }
                    else
                    {
                        decimal T2 = Math.Round(((P / ((x2 * -1) + x1)) + (Anio - 1)), 3);
                        if (T2 > 1)
                        {
                            double valorConDecimal = (double)T2;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec3 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + "s con " + decimales + " mes(es)";
                        }
                        else
                        {
                            double valorConDecimal = (double)T2;
                            long   valorSinDecimal = (long)valorConDecimal;
                            double decimales       = Math.Round((valorConDecimal - (double)valorSinDecimal) * 12, 1);
                            PeridoRec3 = Convert.ToString(valorSinDecimal) + " " + PeriodoSelect + " " + decimales + " mes(es)";
                        }
                    }
                    break;
                }
            }
            else
            {
                PeridoRec3 = "No es posible calcular";
            }
        }
        PeridoRecP2.Add(PeridoRec3);
        ListaFinal.Add(PeridoRecP2);
        /*Calculo de periodo de recuperacion*/

        /*Calculo de beneficio-costo*/
        decimal SumIngresos_actualizados = 0;

        for (int i = 1; i <= Periodo; i++)
        {
            SumIngresos_actualizados = SumIngresos_actualizados + Convert.ToDecimal(ArregloDatos[i, 5]);
        }

        decimal Sum_costos = 0;

        for (int i = 1; i <= Periodo; i++)
        {
            Sum_costos = Sum_costos + Convert.ToDecimal(ArregloDatos[i, 2]);
        }
        Sum_costos = Sum_costos + inversion;
        decimal CRBC = SumIngresos_actualizados / Sum_costos;

        BenCosto.Add("Por cada peso invertido usted obtendra una ganancia de: $" + Convert.ToString(Math.Round(CRBC, 3)));
        ListaFinal.Add(BenCosto);
        /*Calculo de beneficio-costo*/
        String json = JsonConvert.SerializeObject(ListaFinal);

        return(json);
    }
Exemple #43
0
        public void RunMixingMachineProduceNotice(string id)
        {
            SqlHelper     helper = new SqlHelper();
            StringBuilder sql    = new StringBuilder();

            sql.Append(" select pk.sort, pnt.id,p.pnid,p.pmid,pn.name,pm.model,pnt.planQuantity,Convert(varchar ");
            sql.Append(" (10),pnt.startDate,120) as startDate,ei.no,pnt.assessor,pnt.checkupMan,pnt.notifyMan,Convert ");
            sql.Append(" (varchar(10),pnt.notifyDate,120) as notifyDate,psp.ppid,tsp.tpid,ptId,psp.eiid from ");
            sql.Append(" produceNotice pnt,produceSendProportionDetail psp,produceProportion  ");
            sql.Append("  pp,product p,productName pn,productModel pm,productKind pk,targetSendProportionDetail ");

            sql.Append(" tsp,equipmentInformation ei where ei.id=psp.eiid and pnt.spId=psp.spId and psp.ppid=pp.id and pp.pid=p.id and ");
            sql.Append("  p.pnid=pn.id and p.pmid=pm.id and pn.pkid=pk.id and pnt.spid=tsp.spid  ");
            sql.Append(" and pnt.id=" + id);
            sql.Append(" order by notifyDate desc ");

            System.Collections.ArrayList oArrayList = new System.Collections.ArrayList();
            oArrayList.Add(sql.ToString());
            DataSet ds = helper.QueryForDateSet(oArrayList);
            //if (ds.Tables[0].Rows.Count > 0)
            //{
            //    string sendProportionId = ds.Tables[0].Rows[0]["id"];

            //    ArrayList sqlStr = new ArrayList();

            //    sqlStr.Add("");

            //    ProduceDataSet.生产配合比信息DataTable o生产配合比信息DataTable = new ProduceDataSet.生产配合比信息DataTable();
            //    ProduceDataSet.生产配合比信息Row o生产配合比信息Row = (ProduceDataSet.生产配合比信息Row)o生产配合比信息DataTable.NewRow();
            //    o生产配合比信息Row.Proportion1 = "生产配合比编号001";
            //    o生产配合比信息Row.Proportion2 = "沥青1";
            //    o生产配合比信息Row.Proportion3 = "石粉1";
            //    o生产配合比信息Row.Proportion4 = "4_热料仓1";
            //    o生产配合比信息Row.Proportion5 = "5_热料仓1";
            //    o生产配合比信息Row.Proportion6 = "生产配合比编号001";
            //    o生产配合比信息Row.Proportion7 = "沥青1";
            //    o生产配合比信息Row.Proportion8 = "石粉1";
            //    o生产配合比信息Row.ProportionValue1 = "生产配合比编号001";
            //    o生产配合比信息Row.ProportionValue2 = "沥青1";
            //    o生产配合比信息Row.ProportionValue3 = "石粉1";
            //    o生产配合比信息Row.ProportionValue4 = "4_热料仓1";
            //    o生产配合比信息Row.ProportionValue5 = "5_热料仓1";
            //    o生产配合比信息Row.ProportionValue6 = "生产配合比编号001";
            //    o生产配合比信息Row.ProportionValue7 = "沥青1";
            //    o生产配合比信息Row.ProportionValue8 = "石粉1";

            //    o生产配合比信息DataTable.Add生产配合比信息Row(o生产配合比信息Row);
            //    ds.Tables.Add(o生产配合比信息DataTable);

            //    ProduceDataSet.目标配合比信息DataTable o目标配合比信息DataTable = new ProduceDataSet.目标配合比信息DataTable();
            //    ProduceDataSet.目标配合比信息Row o目标配合比信息Row1 = (ProduceDataSet.目标配合比信息Row)o目标配合比信息DataTable.NewRow();
            //    ProduceDataSet.目标配合比信息Row o目标配合比信息Row2 = (ProduceDataSet.目标配合比信息Row)o目标配合比信息DataTable.NewRow();
            //    o目标配合比信息Row1.目标配合比编号 = "目标配合比编号001";
            //    o目标配合比信息Row1.序号 = "序号1";
            //    o目标配合比信息Row1.材料种类 = "材料种类1";
            //    o目标配合比信息Row1.材料名称 = "材料名称1";
            //    o目标配合比信息Row1.规格型号 = "规格型号1";
            //    o目标配合比信息Row1.油石比 = "油石比1";
            //    o目标配合比信息Row1.产地 = "产地1";
            //    o目标配合比信息Row1.生产厂家 = "生产厂家1";

            //    o目标配合比信息Row2.目标配合比编号 = "目标配合比编号001";
            //    o目标配合比信息Row2.序号 = "序号2";
            //    o目标配合比信息Row2.材料种类 = "材料种类2";
            //    o目标配合比信息Row2.材料名称 = "材料名称2";
            //    o目标配合比信息Row2.规格型号 = "规格型号2";
            //    o目标配合比信息Row2.油石比 = "油石比2";
            //    o目标配合比信息Row2.产地 = "产地2";
            //    o目标配合比信息Row2.生产厂家 = "生产厂家2";
            //    o目标配合比信息DataTable.Add目标配合比信息Row(o目标配合比信息Row1);
            //    o目标配合比信息DataTable.Add目标配合比信息Row(o目标配合比信息Row2);

            //    ds.Tables.Add(o目标配合比信息DataTable);
            //}
            MixingMachineProduceNotice oMixingMachineProduceNotice = new MixingMachineProduceNotice();

            oMixingMachineProduceNotice.Source = ds;

            //公司名称
            oMixingMachineProduceNotice.CoName = "中百";
            //编号
            oMixingMachineProduceNotice.Number = "20090101";
            //制表
            oMixingMachineProduceNotice.Tabler = "张三";
            // 部门主管
            oMixingMachineProduceNotice.Manager = "李四";
            //制表日期
            oMixingMachineProduceNotice.CDate = "2009年13月36日";

            oMixingMachineProduceNotice.备注 = "备注";
            // 显示报表
            oMixingMachineProduceNotice.ShowReport();
        }
        /// <summary>
        /// This function converts a polygon shapefile to grid. It implements the line-scan algorithm.
        /// <param name="PolySf">The polygon shapefile</param>
        /// <param name="FldID">The field index</param>
        /// <param name="Newgrd">File name of the new grid</param>
        /// <param name="header">Header object of the new grid</param>
        /// <param name="grType">Grid data type</param>
        /// <param name="cback">can be used to report progress (optional)</param>
        /// <returns>true if successful</returns>
        /// </summary>
        //
        // AUTHOR NAME: Enrico A. Chiaradia
        //       FROM: University of Milan (Italy)
        //     e.mail: [email protected]
        //
        // For details about the line-scan algorithm,
        // please refer to http://www.profc.udec.cl/~gabriel/tutoriales/giswb/vol1/cp3/cp3-6.htm
        //
        // for each shape in PolySf
        // 0) get the shape value (in the shapefile table)
        // 1) load all the borders in a matrix composed by x(startpoint), x(endpoint), slope and share
        // 2) define x of first scan line
        // for each scan lines
        // 3) calculate intersections with polygon border
        // 4) sort intersections from lower Y to the higther
        // 5) convert line space between two consecutive intersection to raster

        public bool Poly2Grid(MapWinGIS.Shapefile PolySf, int FldID, MapWinGIS.Grid Newgrd,
                              MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType,
                              MapWinGIS.ICallback cback)
        {
            double xMin, xMax;
            double x0, x1, x2, y0, y1, y2, m, q;
            int    nShps, nVs, s, nP, p, tempn, v, b;
            object val;
            bool   flg;
            bord   brd;                          //struct to keep a border

            System.Collections.ArrayList bordi2; //list of borders
            int perc = 1;                        //percent shapes done
            int shpsPerc;

            MapWinGIS.Shape PolyShp; //the polygon shape

            //count the number of shapes
            nShps    = PolySf.NumShapes;
            shpsPerc = NumPercentShapes(perc, nShps); //percent of progress

            for (s = 0; s < nShps; ++s)
            {
                //for each shape, determine the extent and the number of parts

                PolyShp = PolySf.get_Shape(s);
                nP      = PolyShp.NumParts;

                xMin = PolyShp.Extents.xMin;
                //yMin = PolyShp.Extents.yMin;
                xMax = PolyShp.Extents.xMax;
                //yMax = PolyShp.Extents.yMax;

                //exclude shapes which are completely outside of the grid extents
                if (!IsGridContainsShape(PolyShp, header))
                {
                    continue;
                }

                //return the shape's value
                val = GetCellValue(PolySf, FldID, s, header.NodataValue);

                //load polygon borders
                nVs    = PolyShp.numPoints - 1;
                bordi2 = new System.Collections.ArrayList(nVs + 1);

                b     = -1;
                tempn = 0;

                for (p = 0; p < nP; ++p)
                {
                    x0 = PolyShp.get_Point(tempn).x;
                    y0 = PolyShp.get_Point(tempn).y;

                    for (v = tempn; v < nVs; ++v)
                    {
                        x1 = PolyShp.get_Point(v).x;
                        x2 = PolyShp.get_Point(v + 1).x;
                        y1 = PolyShp.get_Point(v).y;
                        y2 = PolyShp.get_Point(v + 1).y;

                        if (x1 != x2) // no vertical lines
                        {
                            m = (y2 - y1) / (x2 - x1);
                            q = y1 - (m * x1);

                            //add border to the list
                            b      = b + 1;
                            brd    = new bord();
                            brd.x1 = x1;
                            brd.x2 = x2;
                            brd.m  = m;
                            brd.q  = q;
                            bordi2.Add(brd);
                        }

                        //in case of multi-parts polygon
                        if ((x2 == x0) && (y2 == y0))
                        {
                            tempn = v + 2;
                            break;
                        }
                    } //Next v
                }     // next p

                //define the first line-scan
                double xstart;

                //    20 nov 07 added by Enrico A. Chiaradia
                //necessary if grid extentions differ from shapefile extentions
                if (xMin >= header.XllCenter)
                {
                    xstart = FirstLineXY(xMin, header.XllCenter, header.dX, 1);
                }
                else
                {
                    xstart = FirstLineXY(xMin, header.XllCenter, header.dX, -1);
                }

                // the list of intersection y-values
                System.Collections.ArrayList y_int  = new System.Collections.ArrayList();
                System.Collections.ArrayList pixels = new System.Collections.ArrayList();

                do
                {
                    flg    = Interseca(bordi2, y_int, xstart);
                    flg    = SortArray(y_int);
                    flg    = ScanLine(y_int, xstart, pixels, header, val, cback);
                    xstart = xstart + header.dX;
                }while (xstart <= xMax);

                writePxList(Newgrd, grType, pixels, val, cback);

                //report the progress
                if (s >= shpsPerc)
                {
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                }
            } // next shape

            reportProgress(100, 100, "shapefile to grid", cback); //100 % shapes done
            return(true);
        }
Exemple #45
0
        public void RunYearMaterialRequirementsPlanning(string ppid)
        {
            SqlHelper     helper = new SqlHelper();
            StringBuilder sqlstr = new StringBuilder();

            sqlstr.Append(" select tpd.mid,mn.name,mm.model,mk.sort ");
            sqlstr.Append(",cast(produceQuantity*Proportion as decimal(38, 2))quantity ");
            sqlstr.Append(",cast(january*Proportion as decimal(38, 2))january");
            sqlstr.Append(",cast(february*Proportion as decimal(38, 2)) february");
            sqlstr.Append(",cast(march*Proportion as decimal(38, 2)) march");
            sqlstr.Append(",cast(april*Proportion as decimal(38, 2)) april");
            sqlstr.Append(",cast(may*Proportion as decimal(38, 2)) may");
            sqlstr.Append(",cast(june*Proportion as decimal(38, 2)) june");
            sqlstr.Append(",cast(july*Proportion as decimal(38, 2))july");
            sqlstr.Append(",cast(august*Proportion as decimal(38, 2)) august");
            sqlstr.Append(",cast(september*Proportion as decimal(38, 2))september");
            sqlstr.Append(",cast(october*Proportion as decimal(38, 2))october");
            sqlstr.Append(",cast(november*Proportion as decimal(38, 2))november");
            sqlstr.Append(",cast(december*Proportion as decimal(38, 2))december");
            //sqlstr.Append(",getdate() ");
            sqlstr.Append(" from productionPlanDetail ppd");
            sqlstr.Append(",(");
            sqlstr.Append("	select tpd.tpId,mId,targetProportionValue value,'1' type from targetProportionDetail tpd");
            sqlstr.Append("		union all");
            sqlstr.Append("	select pd.pid tpid,mid,proportionValue value,'2' type from proportionDetail pd");
            sqlstr.Append(") as tpd");
            sqlstr.Append(",(");
            sqlstr.Append("	select tpd.mid,tpd.tpid,tpd.targetProportionValue/(select sum(targetProportionValue) from targetProportionDetail where tpId=tpd.tpid) Proportion,'1' type from targetProportionDetail tpd");
            sqlstr.Append("	union all");
            sqlstr.Append("	select pd.mid,pd.pid as tpid,pd.proportionValue/(select sum(proportionValue) from proportionDetail where pId=pd.pid) Proportion,'2' type from proportionDetail pd");
            sqlstr.Append(") as Proportion");
            sqlstr.Append(",(");
            sqlstr.Append("	select p.id,sort from product p,productName pn,productKind pk where p.pnid=pn.id and pn.pkid=pk.id");
            sqlstr.Append(") as p ,material m,materialName mn,materialModel mm, materialKind mk ");
            sqlstr.Append("where ppd.tpid=tpd.tpid and ppd.tpid=Proportion.tpid and tpd.mid=Proportion.mid and ppd.pid=p.id ");
            sqlstr.Append(" and tpd.mid=m.id and m.mnid=mn.id and m.mmid=mm.id and mn.mkId=mk.id ");
            sqlstr.Append("and Proportion.type=(select case when p.sort='混合料' then 1 else 2 end) ");
            sqlstr.Append("and tpd.type=(select case when p.sort='混合料' then 1 else 2 end) ");
            sqlstr.Append("and ppid=" + ppid);



            System.Collections.ArrayList oArrayList = new System.Collections.ArrayList();
            oArrayList.Add(sqlstr.ToString());
            DataSet ds = helper.QueryForDateSet(oArrayList);

            YearMaterialRequirementsPlanning oYearMaterialRequirementsPlanning = new YearMaterialRequirementsPlanning();

            oYearMaterialRequirementsPlanning.Source = ds;
            //年度
            oYearMaterialRequirementsPlanning.Year = "2009";
            //公司名称
            oYearMaterialRequirementsPlanning.CoName = "中百";
            //文档编号
            oYearMaterialRequirementsPlanning.Number = "20090101";
            //制表
            oYearMaterialRequirementsPlanning.Tabler = "张三";
            //审核
            oYearMaterialRequirementsPlanning.Auditer = "李四";
            //审批
            oYearMaterialRequirementsPlanning.Approvaler = "王五";
            // 显示报表
            oYearMaterialRequirementsPlanning.ShowReport();
        }
Exemple #46
0
 /* Методы для ввода, редактирования и удаления записей*/
 public void addTableItem(TableItem t)
 {
     table.Add(t);
 }
Exemple #47
0
 public void AddItem(string name, string value)
 {
     arrData.Add("\"" + name + "\":" + "\"" + value + "\"");
 }
Exemple #48
0
        }     // public void CloseDataConn( ref SqlConnection dataConnection )

        /// <summary>
        /// private method to parse the cdr
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private ArrayList ParseTheCdr(string fileName)
        {
            // make the array size (number of cdrs per file ) configurable
            System.Collections.ArrayList theControls = new System.Collections.ArrayList(1000);


            // example file formats
            //146148451ce6120071008204847.1711-070000,,Start
            //146158451ce6120071008204858.8531-070000,Javelin_sp,Normal,+14256051047,,Originating,+14256051047,Public,2142498,20071008204858.853,1-070000,Yes,20071008204910.746,20071008205017.699,016,VoIP,,2142498,,,14252142498,,remote,172.27.58.50:5060,[email protected],G729/8000,,,,,,Pacific_Financial_Advisors_gp,,,,,,,,,,y,,,66330:0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,[email protected],,,,,,,,,,,,,,,,,,,,,,,,,,,,20071008205001.004,Success,66330:1,Transfer Consult,,,,,16.157,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
            char[] sep        = new char[] { ',' };
            char[] trim       = new char[] { '"' };
            int    lineNumber = 1;

            try
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        try
                        {
                            // new record
                            BworksCdr aRec = new BworksCdr();

                            // parse the line
                            string[] controls = line.Split(sep);
                            if (controls.GetLength(0) < 100)
                            {
                                // we have a non-data line -- header or footer... so skip it
                                continue;
                            }

                            aRec.recordId        = controls[0].Trim(trim);
                            aRec.serviceProvider = controls[1].Trim(trim);
                            aRec.type            = controls[2].Trim(trim);
                            aRec.userNumber      = controls[3].Trim(trim);
                            aRec.groupNumber     = controls[4].Trim(trim);
                            aRec.direction       = controls[5].Trim(trim);
                            aRec.callingNumber   = controls[6].Trim(trim);
                            aRec.callingPresentationIndicator = controls[7].Trim(trim);
                            aRec.calledNumber              = controls[8].Trim(trim);
                            aRec.startTime                 = controls[9].Trim(trim);
                            aRec.userTimeZone              = controls[10].Trim(trim);
                            aRec.answerIndicator           = controls[11].Trim(trim);
                            aRec.answerTime                = controls[12].Trim(trim);
                            aRec.releaseTime               = controls[13].Trim(trim);
                            aRec.terminationCause          = controls[14].Trim(trim);
                            aRec.networkType               = controls[15].Trim(trim);
                            aRec.carrierIdentificationCode = controls[16].Trim(trim);
                            aRec.dialedDigits              = controls[17].Trim(trim);
                            aRec.callCategory              = controls[18].Trim(trim);
                            aRec.networkCallType           = controls[19].Trim(trim);
                            aRec.networkTranslatedNumber   = controls[20].Trim(trim);
                            aRec.networkTranslatedGroup    = controls[21].Trim(trim);
                            aRec.releasingParty            = controls[22].Trim(trim);
                            aRec.route           = controls[23].Trim(trim);
                            aRec.networkCallId   = controls[24].Trim(trim);
                            aRec.codec           = controls[25].Trim(trim);
                            aRec.group           = controls[31].Trim(trim);
                            aRec.chargeIndicator = controls[41].Trim(trim);
                            aRec.conferenceId    = controls[51].Trim(trim);
                            aRec.userId          = controls[120].Trim(trim);

                            // cache the record
                            theControls.Add(aRec);

                            lineNumber++;
                        }
                        catch (System.Exception ex)
                        {
                            string errorMsg = "Error in File>" + fileName + " Line>" + lineNumber;
                            if (line != null)
                            {// add the line information if available
                                errorMsg += "Line>" + line;
                            }
                            LogFileError(errorMsg + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                        }
                    }
                }
            }// try
            catch (Exception e)
            {
                EventLog.WriteEntry(m_eventLogName, "Error in ParseJobControlFile-- error is " + e.ToString(), EventLogEntryType.Error, 3012);
            }// catch

            return(theControls);
        }// private void ParseJobControlFile()
Exemple #49
0
        public void ParseUl(XmlNodeList items, Node monoTreeNode)
        {
            Node latestNodeAddition = monoTreeNode;

            for (int i = 0; i < items.Count; i++)
            {
                if (items[i].LocalName == "li")
                {
                    string[] attribs = ParseLi(items[i]);

                    string filename = attribs[1];

                    if (i + 1 == items.Count || items[i + 1].LocalName == "ul")
                    {
                        monoTreeNode.tree.HelpSource.Message(TraceLevel.Info,
                                                             spaces + "+" + attribs[0] + ": " + filename);
                        // Put the node in the monodoc toc.

                        // FIXME: Change this to include the help-source ID?
                        // Not really sure what's going on here.....

                        // An empty node with subnodes
                        if (filename == "html/en/empty.html")
                        {
                            // emptysub.html indicates, that a subpage should be generated...
                            // For later use.

                            string exportstr = "<html><head><title>Monodoc</title></head><body><i>Currently Navigation is recommended through the treeview.</i><br />This chapter contains the following entries:<br /><br />";

                            if (items.Count > i + 1 && items[i + 1].HasChildNodes)
                            {
                                foreach (XmlNode node in items[i + 1].ChildNodes)
                                {
                                    if (node.LocalName == "li")
                                    {
                                        string[] list = ParseLi(node);
                                        if (list[1] == "html/en/empty.html")
                                        {
                                            exportstr += list[0] + "<br />";
                                        }
                                        else
                                        {
                                            exportstr += "<a href=\"/" + list[1] + "\">" + list[0] + "</a><br />";
                                        }
                                    }
                                }
                            }

                            exportstr += "</body></html>";
                            Random R  = new Random();
                            string rf = "mgrand_" + R.Next() + ".html";
                            using (FileStream fs = new  FileStream(rf, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                StreamWriter streamWriter = new StreamWriter(fs);

                                streamWriter.WriteLine(exportstr);
                                streamWriter.Close();
                            }

                            filename = rf; //"html/en/emptysub.html";
                            tempfiles.Add(rf);
                        }

                        nodeToAddChildrenTo = latestNodeAddition.CreateNode(attribs[0].Trim(), "xhtml:" + filename);
                    }
                    else
                    {
                        monoTreeNode.tree.HelpSource.Message(TraceLevel.Info,
                                                             spaces + attribs[0] + ": " + filename);
                        // Put the node in the monodoc toc.
                        latestNodeAddition.CreateNode(attribs[0].Trim(), "xhtml:" + filename);
                    }
                    // Put the file in the archive.
                    if (File.Exists(filename))
                    {
                        if (packed_files [filename] == null)
                        {
                            packed_files [filename] = filename;
                            nodeToAddChildrenTo.tree.HelpSource.PackFile(filename, filename);
                        }
                    }

                    string fullpath = Path.Combine(Environment.CurrentDirectory, attribs[1]);
                    if (File.Exists(fullpath))
                    {
                        try
                        {
                            XmlDocument newdoc = new XmlDocument();

                            newdoc.Load(fullpath);
                            IncludeAttribLinks(newdoc.GetElementsByTagName("a"), "href", filename);
                            IncludeAttribLinks(newdoc.GetElementsByTagName("img"), "src", filename);
                            IncludeAttribLinks(newdoc.GetElementsByTagName("link"), "href", filename);
                        }
                        catch
                        {
                            monoTreeNode.tree.HelpSource.Error(spaces + "-- PARSE ERROR --");
                            throw;
                        }
                    }
                }

                if (items[i].LocalName == "ul")
                {
                    spaces += "      ";
                    ParseUl(items[i].ChildNodes, nodeToAddChildrenTo);
                    nodeToAddChildrenTo = latestNodeAddition;
                    spaces = spaces.Substring(6);
                }
            }
        }
Exemple #50
0
        private void WriteAttribute(StreamWriter writer, ref int indent, object o, FieldInfo f, HashSet <object> saved, Dictionary <object, long> idmap, Queue <object> queue, ref int nextID)
        {
            object v = f.GetValue(o);

            if (v == null)
            {
                return;
            }

            this.WriteStartElementAttribute(writer, ref indent, f.Name.TrimStart('_'));

            Type ft = f.FieldType;

            DocXsdFormatEnum?format = GetXsdFormat(f);

            if (format == null || format != DocXsdFormatEnum.Attribute || f.Name.Equals("InnerCoordIndices")) //hackhack -- need to resolve...
            {
                this.WriteOpenElement(writer);
            }

            if (typeof(System.Collections.IEnumerable).IsAssignableFrom(ft))
            {
                System.Collections.IEnumerable list = (System.Collections.IEnumerable)v;

                // for nested lists, flatten; e.g. IfcBSplineSurfaceWithKnots.ControlPointList
                if (typeof(System.Collections.IEnumerable).IsAssignableFrom(ft.GetGenericArguments()[0]))
                {
                    // special case
                    if (f.Name.Equals("InnerCoordIndices")) //hack
                    {
                        foreach (System.Collections.IEnumerable innerlist in list)
                        {
                            string entname = "Seq-IfcPositiveInteger-wrapper"; // hack
                            this.WriteStartElementEntity(writer, ref indent, entname);
                            this.WriteOpenElement(writer);
                            foreach (object e in innerlist)
                            {
                                object ev = e.GetType().GetField("Value").GetValue(e);

                                writer.Write(ev.ToString());
                                writer.Write(" ");
                            }
                            writer.WriteLine();
                            this.WriteEndElementEntity(writer, ref indent, entname);
                        }
                        WriteEndElementAttribute(writer, ref indent, f.Name.TrimStart('_'));
                        return;
                    }

                    System.Collections.ArrayList flatlist = new System.Collections.ArrayList();
                    foreach (System.Collections.ICollection innerlist in list)
                    {
                        foreach (object e in innerlist)
                        {
                            flatlist.Add(e);
                        }
                    }

                    list = flatlist;
                }

                foreach (object e in list)
                {
                    // if collection is non-zero and contains entity instances
                    if (!e.GetType().IsValueType&& !(e is string) && !(e is System.Collections.IEnumerable))
                    {
                        this.WriteCollectionStart(writer, ref indent);
                    }
                    break;
                }

                bool needdelim = false;
                foreach (object e in list)
                {
                    if (e != null) // could be null if buggy file -- not matching schema
                    {
                        if (e is System.Collections.IList)
                        {
                            System.Collections.IList listInner = (System.Collections.IList)e;
                            for (int j = 0; j < listInner.Count; j++)
                            {
                                object oi = listInner[j];

                                Type et = oi.GetType();
                                while (et.IsValueType && !et.IsPrimitive)
                                {
                                    FieldInfo fieldValue = et.GetField("Value");
                                    if (fieldValue != null)
                                    {
                                        oi = fieldValue.GetValue(oi);
                                        et = fieldValue.FieldType;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                // write each value in sequence with spaces delimiting
                                string sval = oi.ToString();
                                writer.Write(sval);
                                writer.Write(" ");
                            }
                        }
                        else if (!e.GetType().IsValueType&& !(e is string))  // presumes an entity
                        {
                            if (needdelim)
                            {
                                this.WriteCollectionDelimiter(writer, indent);
                            }

                            if (format != null && format == DocXsdFormatEnum.Attribute)
                            {
                                // only one item, e.g. StyledByItem\IfcStyledItem
                                this.WriteEntityStart(writer, ref indent);
                                bool closeelem = this.WriteEntityAttributes(writer, ref indent, e, saved, idmap, queue, ref nextID);
                                if (!closeelem)
                                {
                                    this.WriteCloseElementAttribute(writer, ref indent);
                                    return;
                                }
                                this.WriteEntityEnd(writer, ref indent);
                            }
                            else
                            {
                                this.WriteEntity(writer, ref indent, e, saved, idmap, queue, ref nextID);
                            }

                            needdelim = true;
                        }
                        else
                        {
                            // if flat-list (e.g. structural load Locations) or list of strings (e.g. IfcPostalAddress.AddressLines), must wrap
                            this.WriteValueWrapper(writer, ref indent, e);
                        }
                    }
                }

                foreach (object e in list)
                {
                    if (e != null && !e.GetType().IsValueType&& !(e is string))
                    {
                        this.WriteCollectionEnd(writer, ref indent);
                    }
                    break;
                }
            }
            else if (f.FieldType.IsInterface && v is ValueType)
            {
                this.WriteValueWrapper(writer, ref indent, v);
            }
            else if (f.FieldType.IsValueType) // must be IfcBinary
            {
                FieldInfo fieldValue = f.FieldType.GetField("Value");
                if (fieldValue != null)
                {
                    v = fieldValue.GetValue(v);
                    if (v is byte[])
                    {
                        this.WriteOpenElement(writer);

                        // binary data type - we don't support anything other than 8-bit aligned, though IFC doesn't either so no point in supporting extraBits
                        byte[] bytes = (byte[])v;

                        StringBuilder sb = new StringBuilder(bytes.Length * 2);
                        for (int i = 0; i < bytes.Length; i++)
                        {
                            byte b = bytes[i];
                            sb.Append(HexChars[b / 0x10]);
                            sb.Append(HexChars[b % 0x10]);
                        }
                        v = sb.ToString();
                        writer.WriteLine(v);
                    }
                }
            }
            else
            {
                if (format != null && format == DocXsdFormatEnum.Attribute)
                {
                    this.WriteEntityStart(writer, ref indent);

                    Type vt = v.GetType();
                    if (ft != vt)
                    {
                        this.WriteType(writer, indent, vt.Name);
                    }

                    bool closeelem = this.WriteEntityAttributes(writer, ref indent, v, saved, idmap, queue, ref nextID);

                    if (!closeelem)
                    {
                        this.WriteCloseElementEntity(writer, ref indent);
                        return;
                    }

                    this.WriteEntityEnd(writer, ref indent);
                }
                else
                {
                    // if rooted, then check if we need to use reference; otherwise embed
                    this.WriteEntity(writer, ref indent, v, saved, idmap, queue, ref nextID);
                }
            }

            WriteEndElementAttribute(writer, ref indent, f.Name.TrimStart('_'));
        }
Exemple #51
0
        public string KeyGenrator()
        {
            //*****************starts of prime number genrator******************
            System.Collections.ArrayList arr = new System.Collections.ArrayList();
            int cnt      = 1;
            int InnerCnt = 1;
            int InnerDiv = 0;

            for (cnt = 1; cnt < 300; cnt++)
            {
                InnerDiv = 0;
                for (InnerCnt = cnt; InnerCnt > 0; InnerCnt--)
                {
                    if (cnt % InnerCnt == 0)
                    {
                        InnerDiv++;
                    }
                }
                if (InnerDiv <= 2)
                {
                    arr.Add(cnt);
                }
            }
            //*****************end of Prime Number******************
            int    arrayCount       = arr.Count - 5;
            Random rdn              = new Random();
            int    randomNoForPrime = rdn.Next(15, arrayCount);

            int p   = Convert.ToInt32(arr[randomNoForPrime]);
            int q   = Convert.ToInt32(arr[randomNoForPrime + 2]);
            int n   = p * q;
            int phi = (p - 1) * (q - 1);

            //********Public Key Genration************
            int    e            = 3;
            Random rde          = new Random();
            int    randomNoForE = rde.Next(10, arrayCount);

            e = Convert.ToInt32(arr[randomNoForE]);
            if (n / e == 0)
            {
                KeyGenrator();
            }
            //********Private Key Genration***********
            int d         = 2;
            int remainder = 0;

            while (remainder != 1)
            {
                d++;
                remainder = (e * d) % phi;
                if (d == phi)//thsi code is written for chek that 'd' is less then 'phi'
                {
                    remainder = 1;
                    KeyGenrator();
                }
            }


            //********Sending the public and private key********
            string sn = n.ToString();
            string se = e.ToString();
            string sd = d.ToString();

            MessageBox.Show("Congradualtion:\nYou Have Genrated Public and Private Keys Successfuly.\n\nYour\n Public key   :     " + se + "," + sn + "\n Private Key  :     " + sd + "," + sn + "\n\nPress Ok to Proceede");

            StringBuilder sb = new StringBuilder();

            sb.Append(se + "," + sn + "." + sd + "," + sn);
            string st = sb.ToString();

            return(st);
        }
Exemple #52
0
        private void Initialize()
        {
            ReportMenu.SubGroups = new ArrayList();

            MonthsDT = new DataTable();
            MonthsDT.Columns.Add(new DataColumn("MonthID", Type.GetType("System.Int32")));
            MonthsDT.Columns.Add(new DataColumn("MonthName", Type.GetType("System.String")));

            for (int i = 1; i <= 12; i++)
            {
                DataRow NewRow = MonthsDT.NewRow();
                NewRow["MonthID"]   = i;
                NewRow["MonthName"] = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).ToString();
                MonthsDT.Rows.Add(NewRow);
            }
            cbxMonths.DataSource    = MonthsDT.DefaultView;
            cbxMonths.ValueMember   = "MonthID";
            cbxMonths.DisplayMember = "MonthName";

            DateTime LastDay = new System.DateTime(DateTime.Now.Year, 12, 31);

            System.Collections.ArrayList Quarters = new System.Collections.ArrayList();
            System.Collections.ArrayList Years    = new System.Collections.ArrayList();
            for (int i = 1; i <= 4; i++)
            {
                Quarters.Add(i);
            }
            for (int i = 2013; i <= LastDay.Year; i++)
            {
                Years.Add(i);
            }
            cbxQuarters.DataSource    = Quarters.ToArray();
            cbxQuarters.SelectedIndex = 0;
            cbxYears.DataSource       = Years.ToArray();
            cbxYears.SelectedIndex    = cbxYears.Items.Count - 1;

            GroupsDT    = new DataTable();
            SubGroupsDT = new DataTable();
            GroupsBS    = new BindingSource();
            SubGroupsBS = new BindingSource();

            if (StoreType == 1)
            {
                using (System.Data.SqlClient.SqlDataAdapter DA = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM TechStoreGroups" +
                                                                                                          " WHERE TechStoreGroupID IN (SELECT TechStoreGroupID FROM TechStoreSubGroups WHERE TechStoreSubGroupID IN" +
                                                                                                          " (SELECT TechStoreSubGroupID FROM TechStore WHERE TechStoreID IN (SELECT DISTINCT StoreItemID FROM infiniu2_storage.dbo.Store" +
                                                                                                          " WHERE FactoryID = " + FactoryID + ")))" +
                                                                                                          " ORDER BY TechStoreGroupName", ConnectionStrings.CatalogConnectionString))
                {
                    DA.Fill(GroupsDT);
                    GroupsDT.Columns.Add(new DataColumn("Checked", Type.GetType("System.Boolean")));
                    foreach (DataRow Row in GroupsDT.Rows)
                    {
                        Row["Checked"] = false;
                    }
                }
                using (System.Data.SqlClient.SqlDataAdapter DA = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM TechStoreSubGroups WHERE TechStoreSubGroupID IN" +
                                                                                                          " (SELECT TechStoreSubGroupID FROM TechStore WHERE TechStoreID IN (SELECT DISTINCT StoreItemID FROM infiniu2_storage.dbo.Store" +
                                                                                                          " WHERE FactoryID = " + FactoryID + "))" +
                                                                                                          " ORDER BY TechStoreSubGroupName", ConnectionStrings.CatalogConnectionString))
                {
                    DA.Fill(SubGroupsDT);
                    SubGroupsDT.Columns.Add(new DataColumn("Checked", Type.GetType("System.Boolean")));
                    foreach (DataRow Row in SubGroupsDT.Rows)
                    {
                        Row["Checked"] = false;
                    }
                }
            }
            if (StoreType == 2)
            {
                using (System.Data.SqlClient.SqlDataAdapter DA = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM TechStoreGroups" +
                                                                                                          " WHERE TechStoreGroupID IN (SELECT TechStoreGroupID FROM TechStoreSubGroups WHERE TechStoreSubGroupID IN" +
                                                                                                          " (SELECT TechStoreSubGroupID FROM TechStore WHERE TechStoreID IN (SELECT DISTINCT StoreItemID FROM infiniu2_storage.dbo.ManufactureStore" +
                                                                                                          " WHERE FactoryID = " + FactoryID + ")))" +
                                                                                                          " ORDER BY TechStoreGroupName", ConnectionStrings.CatalogConnectionString))
                {
                    DA.Fill(GroupsDT);
                    GroupsDT.Columns.Add(new DataColumn("Checked", Type.GetType("System.Boolean")));
                    foreach (DataRow Row in GroupsDT.Rows)
                    {
                        Row["Checked"] = false;
                    }
                }
                using (System.Data.SqlClient.SqlDataAdapter DA = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM TechStoreSubGroups WHERE TechStoreSubGroupID IN" +
                                                                                                          " (SELECT TechStoreSubGroupID FROM TechStore WHERE TechStoreID IN (SELECT DISTINCT StoreItemID FROM infiniu2_storage.dbo.ManufactureStore" +
                                                                                                          " WHERE FactoryID = " + FactoryID + "))" +
                                                                                                          " ORDER BY TechStoreSubGroupName", ConnectionStrings.CatalogConnectionString))
                {
                    DA.Fill(SubGroupsDT);
                    SubGroupsDT.Columns.Add(new DataColumn("Checked", Type.GetType("System.Boolean")));
                    foreach (DataRow Row in SubGroupsDT.Rows)
                    {
                        Row["Checked"] = false;
                    }
                }
            }
            GroupsBS.DataSource    = GroupsDT;
            SubGroupsBS.DataSource = SubGroupsDT;

            GroupsGridSettings();
            SubGroupsGridSettings();
        }
Exemple #53
0
        //NECESSITA SER ASYNC POR TER QUE AGUARDAR A RESPOSTA DA API
        public static async Task Main(string[] args)

        {
            Console.WriteLine("Consultando Ceps");
            // Abrir arquivo excel existente

            var tabela   = new XLWorkbook(@"C:\Users\caio.telles\Desktop\importar_bairros\bairro-taxa.xlsx"); //coloca o caminho da pasta com o arquivo XLSM do EXCEL
            var planilha = tabela.Worksheet(1);

            //  Console.WriteLine("".PadRight('-'));
            // Console.WriteLine("Bairros".PadRight(35) + "Taxa".PadRight(15) + "Entrega".PadRight(15));
            System.Collections.ArrayList Ceps = new System.Collections.ArrayList();

            //CRIAÇÃO DE VARIAVEIS
            var linha = 2;                                                                  //CONTADOR DE LINHAS EXCEL

            string ok = "nao";                                                              //STRING DE REECONFIRMAÇÃO

            System.Collections.ArrayList CepsValidos = new System.Collections.ArrayList();  //CRIAÇÃO DE ARRAY
            var    Faixa        = planilha.Cell("a" + linha.ToString()).Value.ToString();   //CONVERSAO DE STRING FAIXA DOS CEPS
            var    FaixaInicial = (planilha.Cell("b" + linha.ToString()).Value.ToString()); ////CONVERSAO DE STRING FAIXAINICIAL DOS CEPS
            var    FaixaFinal   = (planilha.Cell("c" + linha.ToString()).Value.ToString()); //CONVERSAO DE STRING FAIXAFINAL DOS CEPS
            var    lInicio      = int.Parse(FaixaInicial);                                  //CONVERSAO PARA USAR NA LOGICA FAIXA INICIAL
            var    lfim         = int.Parse(FaixaFinal);                                    ////CONVERSAO PARA USAR NA LOGICA FAIXA FINAL
            var    Lok          = int.Parse(FaixaInicial);                                  // VARIAVEL PARA INCRIMENTAR TODOS OS CEPS PROCURADOS
            string Validcep     = Lok.ToString();                                           //TRANSFORMAR PARA STRING


            while (true)
            {
                while (true)
                {
                    if (Lok <= lfim) // LINHA DO CEP NAO PODE SER MAIOR QUE A FAIXA FINAL
                    {
                        Lok++;       //INCRIMENTA O CEP

                        Validcep = Lok.ToString();
                        Ceps.Add(Validcep);                                 //ADICIONA NO ARRAY
                        ConsultaCEP(ok, linha, Lok, Validcep, CepsValidos); //CHAMA A FUNÇÃO DE CONSULTA API
                    }

                    if (Lok > lfim)//CASO O CEP SEJA MAIOR QUE A FAIXA FINAL PULA PARA A PROXIMA LINHA , OBS NÃO PODE SER VAZIA A LINHA
                    {
                        //ATRIBUIS NOVOS VALORES PARA A VARIAVEL DE FAIXAS E SOMA A LINHA
                        linha++;
                        Faixa        = planilha.Cell("a" + linha.ToString()).Value.ToString();
                        FaixaInicial = (planilha.Cell("b" + linha.ToString()).Value.ToString());
                        FaixaFinal   = (planilha.Cell("c" + linha.ToString()).Value.ToString());

                        //VERIFICA SE A LINHA ESTÁ VAZIA
                        if (string.IsNullOrEmpty(Faixa) ||
                            string.IsNullOrEmpty(FaixaInicial) ||
                            string.IsNullOrEmpty(FaixaFinal)
                            )
                        {
                            //CASO ESTEJA VAZIA CHAMA A FUNÇÃO DE CONSULTA PASSANDO SIM , PARA INICIAR A CRIAÇÃO DO EXCEL
                            Validcep = Lok.ToString();
                            Ceps.Add(Validcep);
                            ok = "sim";//PROVOCA A CRIAÇÃO DO EXCEL
                            ConsultaCEP(ok, linha, Lok, Validcep, CepsValidos);
                            break;
                        }
                        lInicio = int.Parse(FaixaInicial);
                        lfim    = int.Parse(FaixaFinal);
                        Lok     = int.Parse(FaixaInicial);
                    }

                    break;
                }
            }
        }
        /// <summary>
        /// CSVをArrayListに変換
        /// </summary>
        /// <param name="csvText">CSVの内容が入ったString</param>
        /// <returns>変換結果のArrayList</returns>
        public ArrayList CsvToArrayList1(string csvText)
        {
            System.Collections.ArrayList csvRecords =
                new System.Collections.ArrayList();

            //前後の改行を削除しておく
            csvText = csvText.Trim(new char[] { '\r', '\n' });

            //一行取り出すための正規表現
            System.Text.RegularExpressions.Regex regLine =
                new System.Text.RegularExpressions.Regex(
                    "^.*(?:\\n|$)",
                    System.Text.RegularExpressions.RegexOptions.Multiline);

            //1行のCSVから各フィールドを取得するための正規表現
            System.Text.RegularExpressions.Regex regCsv =
                new System.Text.RegularExpressions.Regex(
                    "\\s*(\"(?:[^\"]|\"\")*\"|[^,]*)\\s*,",
                    System.Text.RegularExpressions.RegexOptions.None);

            System.Text.RegularExpressions.Match mLine = regLine.Match(csvText);
            while (mLine.Success)
            {
                //一行取り出す
                string line = mLine.Value;
                //改行記号が"で囲まれているか調べる
                while ((CountString(line, "\"") % 2) == 1)
                {
                    mLine = mLine.NextMatch();
                    if (!mLine.Success)
                    {
                        throw new ApplicationException("不正なCSV");
                    }
                    line += mLine.Value;
                }
                //行の最後の改行記号を削除
                line = line.TrimEnd(new char[] { '\r', '\n' });
                //最後に「,」をつける
                line += ",";

                //1つの行からフィールドを取り出す
                System.Collections.ArrayList csvFields =
                    new System.Collections.ArrayList();
                System.Text.RegularExpressions.Match m = regCsv.Match(line);
                while (m.Success)
                {
                    string field = m.Groups[1].Value;
                    //前後の空白を削除
                    field = field.Trim();
                    //"で囲まれている時
                    if (field.StartsWith("\"") && field.EndsWith("\""))
                    {
                        //前後の"を取る
                        field = field.Substring(1, field.Length - 2);
                        //「""」を「"」にする
                        field = field.Replace("\"\"", "\"");
                    }
                    csvFields.Add(field);
                    m = m.NextMatch();
                }

                csvFields.TrimToSize();
                csvRecords.Add(csvFields);

                mLine = mLine.NextMatch();
            }

            csvRecords.TrimToSize();
            return(csvRecords);
        }
        // this method is called by SecurityInfoCCW.GetSecurity
        // its return is the SecurityDescriptor in binary format
        // it loads the data from the registry
        // [loads data from registry to UI]
        public IntPtr GetSecurity(SecurityInfos requestedInformation, bool wantDefault)
        {
            if (requestedInformation == SecurityInfos.DiscretionaryAcl)
            {
                StringBuilder securityDescriptorBuilder = new StringBuilder("D:");

                System.Collections.ArrayList kerb = new System.Collections.ArrayList(current.KerberosGlobalAcl);
                System.Collections.ArrayList indexesOfInvalidItems = new System.Collections.ArrayList();
                for (int i = 0; i < kerb.Count; i++)
                {
                    try
                    {
                        string sid = ((new NTAccount((string)kerb[i])).Translate(typeof(SecurityIdentifier))).ToString();
                        securityDescriptorBuilder.Append("(A;;LCSWRP;;;" + sid + ")");
                    }
                    catch (ArgumentException) // invalid account, do not consider it
                    {
                        indexesOfInvalidItems.Add(i);
                    }
                    catch (IdentityNotMappedException)
                    {
                        indexesOfInvalidItems.Add(i);
                    }
                }

                //remove invalid items based on indexesOfInvalidItems
                for (int i = indexesOfInvalidItems.Count - 1; i >= 0; i--)
                {
                    kerb.RemoveAt((int)indexesOfInvalidItems[i]);
                }

                // rebuild the ACL, taking care not to leave it null
                if (kerb.Count <= 0)
                {
                    current.KerberosGlobalAcl = new string[] { "" };
                }
                else
                {
                    current.KerberosGlobalAcl = (string[])kerb.ToArray(typeof(string));
                }

                IntPtr securityDescriptor;
                int    size = 0;

                // call external function for transformig String SecurityDescriptors
                // into their internal representation
#pragma warning suppress 56523
                bool ret = SafeNativeMethods.ConvertStringSecurityDescriptorToSecurityDescriptor(
                    securityDescriptorBuilder.ToString(),
                    1, /*
                        * must be SDDL_REVISION_1 == 1 always
                        */
                    out securityDescriptor,
                    out size
                    );
                if (!ret)
                {
                    return(IntPtr.Zero);
                }
                return(securityDescriptor);
            }
            return(IntPtr.Zero);
        }
Exemple #56
0
 public Cube()
 {
     Draw = new System.Collections.ArrayList();
     Draw.Add(Root.Instance.ResourceManager.LoadMesh("cube/cube.mesh"));
 }
Exemple #57
0
        /// <summary>
        /// 向发送客户端发送数据事情
        /// </summary>
        /// <param name="data">发送的数据</param>
        /// <param name="endResponse"></param>
        public void Send(WebMeta data, bool endResponse)
        {
            WebResponse response = this.Response;

            if (data.ContainsKey("type") && data["type"] == "UI.Event")
            {
                if (runtime.Client.UIEvent != null)
                {
                    var click = runtime.Client.UIEvent;
                    var key   = data["key"];
                    if (String.Equals(key, "Click") && data.GetDictionary()["value"] is ListItem)
                    {
                        runtime.Client.UIEvent = null;
                        runtime.Client.Session.Storage(new Hashtable(), this);
                        var value    = data.GetDictionary()["value"] as ListItem;
                        var objValue = click.Send();
                        if (objValue is Hashtable)
                        {
                            var val = objValue as Hashtable;
                            var em  = val.GetEnumerator();

                            while (em.MoveNext())
                            {
                                if (String.Equals(em.Value, "Value"))
                                {
                                    val[em.Key] = value.Value;
                                    val[String.Format("{0}_Text", em.Key)] = value.Text;
                                    //val.Put(em.Key as string, value.Value);
                                    break;
                                }
                            }
                            response.Redirect(click.Model, click.Command, new WebMeta(val), false);
                        }
                        else if (objValue is WebMeta)
                        {
                            var val = objValue as WebMeta;
                            var em  = val.GetDictionary().GetEnumerator();

                            while (em.MoveNext())
                            {
                                if (String.Equals(em.Value, "Value"))
                                {
                                    val.Put(em.Key as string, value.Value);
                                    val[String.Format("{0}_Text", em.Key)] = value.Text;
                                    break;
                                }
                            }

                            response.Redirect(click.Model, click.Command, val, false);
                        }
                        else
                        {
                            response.Redirect(click.Model, click.Command, value.Value, false);
                        }
                    }
                }
            }
            response.ClientEvent |= WebEvent.DataEvent;
            if (response.Headers.ContainsKey("DataEvent"))
            {
                var ts = response.Headers.GetDictionary()["DataEvent"];
                if (ts is WebMeta)
                {
                    response.Headers.Set("DataEvent", (WebMeta)ts, data);
                }
                else if (ts is IDictionary)
                {
                    response.Headers.Set("DataEvent", new WebMeta((IDictionary)ts), data);
                }
                else if (ts is Array)
                {
                    var ats = new System.Collections.ArrayList();
                    ats.AddRange((Array)ts);
                    ats.Add(data);

                    response.Headers.Set("DataEvent", (WebMeta[])ats.ToArray(typeof(WebMeta)));
                }
                else
                {
                    response.Headers.Set("DataEvent", data);
                }
            }
            else
            {
                response.Headers.Set("DataEvent", data);
            }
            if (endResponse)
            {
                response.ClientEvent ^= response.ClientEvent & WebEvent.Normal;
                this.End();
            }
        }
Exemple #58
0
 public Floor()
 {
     Draw = new System.Collections.ArrayList();
     Draw.Add(Root.Instance.ResourceManager.LoadMesh("floor/floor.mesh"));
 }
Exemple #59
0
        //Clearing Text Of List Of Files
        public string ClearingTextOfListOfFiles(string TextOfListOfFiles)
        {
            //
            string ClearedTextOfListOfFiles = "";

            System.Collections.ArrayList ListOfNamesOfFiles = new System.Collections.ArrayList();
            //
            // Replacing <BR> To 13
            //
            TextOfListOfFiles = TextOfListOfFiles.Replace("<BR>", String.Format("{0}", (char)13));
            //
            // Division Of Text Of List Of Files
            //
            //string[] Separator = new string[1] { String.Format("{0}{1}", (char)13, (char)10) };
            string[] Separator = new string[2] {
                String.Format("{0}", (char)10), String.Format("{0}", (char)13)
            };
            string[] StringsOfListOfFiles =
                TextOfListOfFiles.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
            //
            // Getting Name Of File
            //
            for (int i = 0; i < StringsOfListOfFiles.Length; i++)
            {
                //
                if (StringsOfListOfFiles[i].Length > 0)
                {
                    //
                    // Checking Existence Of Tag A
                    //
                    int IndexOfBeginningA = StringsOfListOfFiles[i].IndexOf("<A ");
                    int IndexOfEndA       = StringsOfListOfFiles[i].IndexOf(">");
                    //
                    if ((IndexOfBeginningA > -1) && (IndexOfEndA > -1))
                    {
                        //
                        // Getting Text Of Tag A
                        //
                        string TextOfA = "";
                        //
                        if (IndexOfEndA >= IndexOfBeginningA)
                        {
                            TextOfA =
                                StringsOfListOfFiles[i].Substring(IndexOfBeginningA, IndexOfEndA - IndexOfBeginningA);
                        }
                        //
                        // Checking Existence Of Name
                        //
                        int IndexOfBeginningName = TextOfA.IndexOf("\"");
                        int IndexOfEndName       = TextOfA.LastIndexOf("\"");
                        //
                        if ((IndexOfBeginningName > -1) && (IndexOfEndName > -1))
                        {
                            //
                            // Getting Name Of File
                            //
                            string NameOfFile = "";
                            //
                            IndexOfBeginningName += 1;
                            //
                            if (IndexOfEndName >= IndexOfBeginningName)
                            {
                                NameOfFile =
                                    TextOfA.Substring(IndexOfBeginningName, IndexOfEndName - IndexOfBeginningName);
                            }
                            //
                            // Checking Name
                            //
                            if (NameOfFile.IndexOf("/") > -1)
                            {
                                //
                                string[] ElementsOfNameOfFile =
                                    NameOfFile.Split(new char[1] {
                                    '/'
                                }, StringSplitOptions.RemoveEmptyEntries);
                                //
                                if (ElementsOfNameOfFile.Length > 0)
                                {
                                    NameOfFile = ElementsOfNameOfFile[ElementsOfNameOfFile.GetUpperBound(0)];
                                }
                                else
                                {
                                    NameOfFile = "";
                                }
                            }
                            //
                            if (NameOfFile.IndexOf("..") > -1)
                            {
                                NameOfFile = "";
                            }
                            //
                            // Addition Of Name
                            //
                            if (NameOfFile != "")
                            {
                                ListOfNamesOfFiles.Add(NameOfFile);
                            }
                        }
                    }
                }
            }
            //
            // Generation Of Text Of List Of Names Of Files
            //
            foreach (string CurrentName in ListOfNamesOfFiles)
            {
                ClearedTextOfListOfFiles += CurrentName + String.Format("{0}{1}", (char)13, (char)10);
            }
            //
            // Return
            //
            return(ClearedTextOfListOfFiles);
        }
Exemple #60
0
 public Car()
 {
     Draw = new System.Collections.ArrayList();
     Draw.Add(new Marker());
 }