private static StringCollection BuildList()
 {
     StringCollection list = new StringCollection();
     list.Add("ABC");
     list.Add("DEF");
     list.Add("GHI");
     return list;
 }
Esempio n. 2
0
File: test.cs Progetto: mono/gert
	static int Main (string [] args)
	{
		if (args.Length != 1) {
			Console.WriteLine ("Please specify action.");
			return 1;
		}

		switch (args [0]) {
		case "clear":
			Settings.Default.Name = null;
			Settings.Default.FirstNames = null;
			Settings.Default.Address = null;
			Settings.Default.Save ();
			break;
		case "delete":
			Configuration config = ConfigurationManager.OpenExeConfiguration (
				ConfigurationUserLevel.PerUserRoamingAndLocal);
			File.Delete (config.FilePath);
			break;
		case "write":
			StringCollection firstNames = new StringCollection ();
			firstNames.Add ("Miguel");
			firstNames.Add ("Atsushi");
			firstNames.Add ("Gonzalo");

			Settings.Default.Address = new Address ("Whatever", 50);
			Settings.Default.FirstNames = firstNames;
			Settings.Default.Name = "Mono";
			Settings.Default.Save ();
			break;
		case "read1":
			Assert.IsNotNull (Settings.Default.Address, "#1");
			Assert.AreEqual (50, Settings.Default.Address.HouseNumber, "#2");
			Assert.AreEqual ("Whatever", Settings.Default.Address.Street, "#3");
			Assert.IsNotNull (Settings.Default.FirstNames, "#4");
			Assert.AreEqual (3, Settings.Default.FirstNames.Count, "#5");
			Assert.AreEqual ("Miguel", Settings.Default.FirstNames [0], "#6");
			Assert.AreEqual ("Atsushi", Settings.Default.FirstNames [1], "#7");
			Assert.AreEqual ("Gonzalo", Settings.Default.FirstNames [2], "#8");
			Assert.AreEqual ("Mono", Settings.Default.Name, "#9");
			break;
		case "read2":
			Assert.AreEqual (string.Empty, Settings.Default.Name, "#1");
			Assert.IsNull (Settings.Default.FirstNames, "#2");
			Assert.IsNull (Settings.Default.Address, "#3");
			break;
		case "read3":
			Assert.IsNull (Settings.Default.Name, "#1");
			Assert.IsNull (Settings.Default.FirstNames, "#2");
			Assert.IsNull (Settings.Default.Address, "#3");
			break;
		default:
			Console.WriteLine ("Unsupported action '{0}'.", args [0]);
			return 2;
		}

		return 0;
	}
		public void GetOrderTransactions()
		{
			//
			GetOrderTransactionsCall api = new GetOrderTransactionsCall(
			this.apiContext);
			StringCollection idArray = new StringCollection();
			api.OrderIDArrayList = idArray;
			idArray.Add("1111111111");
			//ItemTransactionIDTypeCollection tIdArray = new ItemTransactionIDTypeCollection();
			//api.ItemTransactionIDArrayList = tIdArray;
			//ItemTransactionIDType tId = new ItemTransactionIDType();
			//tIdArray.Add(tId);
			//String itemId = "2222222222";
			//tId.ItemID = itemId;
			//tId.TransactionID = "test transaction id";
			// Make API call.
			ApiException gotException = null;
			try {
			OrderTypeCollection orders = api.GetOrderTransactions(idArray);
			} catch (ApiException ex) {
				gotException = ex;
			}
			Assert.IsNull(gotException);
			
		}
        public void GetProductSearchResults()
        {
            this.apiContext.Timeout = 360000;
            GetProductSearchResultsCall api = new GetProductSearchResultsCall(this.apiContext);
            ProductSearchType ps = new ProductSearchType();
            //ps.AttributeSetID = 1785;// Cell phones
            ps.MaxChildrenPerFamily = 20; ps.MaxChildrenPerFamilySpecified = true;
            ps.AvailableItemsOnly = false; ps.AvailableItemsOnlySpecified = true;
            ps.QueryKeywords = "Nokia";
            StringCollection ids = new StringCollection();
            ids.Add("1785");
            ps.CharacteristicSetIDs = ids;
            // Pagination
            PaginationType pt = new PaginationType();
            pt.EntriesPerPage = 50; pt.EntriesPerPageSpecified = true;
            pt.PageNumber = 1; pt.PageNumberSpecified = true;
            ps.Pagination = pt;

            ProductSearchTypeCollection pstc = new ProductSearchTypeCollection();
            pstc.Add(ps);
            // Make API call.
            ProductSearchResultTypeCollection results = api.GetProductSearchResults(pstc);
            Assert.IsNotNull(results);
            Assert.IsTrue(results.Count > 0);
            TestData.ProductSearchResults = results;
            Assert.IsNotNull(TestData.ProductSearchResults);
            Assert.IsTrue(TestData.ProductSearchResults.Count > 0);
        }
Esempio n. 5
0
    public StringCollection GetTargetIds(string parameterValues)
    {
      StringCollection ids = new StringCollection();

      try
      {
        Configuration.LayerFunctionRow layerFunction = GetLayerFunctionRows().First(o => o.FunctionName == "targetparams");

        using (OleDbCommand command = layerFunction.GetDatabaseCommand())
        {
          string[] p = parameterValues.Split(',');

          for (int i = 0; i < command.Parameters.Count - 1; ++i)
          {
            command.Parameters[i].Value = p[i];
          }

          command.Parameters[command.Parameters.Count - 1].Value = AppUser.GetRole();

          using (OleDbDataReader reader = command.ExecuteReader())
          {
            while (reader.Read())
            {
              ids.Add(reader.GetValue(0).ToString());
            }
          }
        }
      }
      catch { }

      return ids;
    }
		public void RelistItemFull()
		{

			Assert.IsNotNull(TestData.EndedItem2);
			
			TestData.EndedItem2.ApplicationData="this is new appilcation data which is specified by "+DateTime.Now.ToShortDateString();
			RelistItemCall rviCall = new RelistItemCall(this.apiContext);
			ItemType item = TestData.EndedItem2;
			item.CategoryMappingAllowed=true;
			item.CategoryMappingAllowed=true;

			rviCall.Item=item;
			StringCollection fields =new StringCollection();
			String field="Item.ApplicationData";
			fields.Add(field);
			rviCall.DeletedFieldList=fields;
			rviCall.Execute();

			//check whether the call is success.
			Assert.IsTrue(rviCall.AbstractResponse.Ack==AckCodeType.Success || rviCall.AbstractResponse.Ack==AckCodeType.Warning,"do not success!");
			Assert.IsNotNull(rviCall.FeeList,"the Fees is null");
			/*
			foreach(FeeType fee in rviCall.FeeList)
			{
				isTherePropertyNull=ReflectHelper.IsProperteValueNotNull(fee,out nullPropertyNums,out nullPropertyNames);
				Assert.IsTrue(isTherePropertyNull,"there are" +nullPropertyNums.ToString()+ " properties value is null. (" +nullPropertyNames+ ")");
			}*/
			Assert.IsNotNull(rviCall.ItemID,"the ItemID is null");
			Assert.IsNotNull(rviCall.StartTime ,"the StartTime is null");

			//Assert.IsTrue(false,"NewItem:"+TestData.NewItem.ItemID+";EndedItem:"+TestData.EndedItem.ItemID+";NewItem2:"+TestData.NewItem2.ItemID+";EndedItem2:"+TestData.EndedItem2.ItemID);

		}
Esempio n. 7
0
File: test.cs Progetto: mono/gert
	static void Main ()
	{
		AppDomainSetup setup = new AppDomainSetup ();
		setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
		setup.ApplicationName = "test";

		AppDomain newDomain = AppDomain.CreateDomain ("test",
			AppDomain.CurrentDomain.Evidence, setup);

		StringCollection probePaths = new StringCollection ();
		probePaths.Add (Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "lib"));

		// create an instance of our custom Assembly Resolver in the target domain.
		newDomain.CreateInstanceFrom (Assembly.GetExecutingAssembly ().CodeBase,
			typeof (AssemblyResolveHandler).FullName,
			false,
			BindingFlags.Public | BindingFlags.Instance,
			null,
			new object[] { probePaths },
			CultureInfo.InvariantCulture,
			null,
			AppDomain.CurrentDomain.Evidence);

		Helper helper = new Helper ();
		newDomain.DoCallBack (new CrossAppDomainDelegate (helper.Test));
	}
    private void BCCAgentIndicator()
    {
        try
        {
            StringCollection serviceList = new StringCollection();
            serviceList.Add(ConfigurationManager.AppSettings["BCCAgentName"].ToString());

            if (serviceList != null && serviceList.Count > 0)
            {
                BCCOperator bccOperator = new BCCOperator();
                DataTable dtService = bccOperator.GetServiceStatus(serviceList);

                if (dtService != null && dtService.Rows != null && dtService.Rows.Count > 0)
                {
                    string agent = "BCC Agent";
                    agentName.Text = agent;
                    agentStatus.Status = dtService.Rows[0][1].ToString();
                    agentStatus.ToolTip = dtService.Rows[0][1].ToString();
                    agentName.ToolTip = agent + " - " + dtService.Rows[0][1].ToString();
                }
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.Write(ex.Message + ex.StackTrace, "Controls_AgentIndicator");
        }
    }
Esempio n. 9
0
 /// <summary>
 /// Creates a relative path from one file or folder to another.
 /// </summary>
 /// <param name="fromDirectory">Contains the directory that defines the start of the relative path.</param>
 /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
 /// <returns>The relative path from the start directory to the end path.</returns>
 /// <exception cref="ArgumentNullException"></exception>
 /// <exception cref="ArgumentException"></exception>
 public static string RelativePathTo(string fromDirectory, string toPath)
 {
     if(fromDirectory == null)
         throw new ArgumentNullException("fromDirectory");
     if(toPath == null)
         throw new ArgumentNullException("fromDirectory");
     if(System.IO.Path.IsPathRooted(fromDirectory) && System.IO.Path.IsPathRooted(toPath))
     {
         if(string.Compare(System.IO.Path.GetPathRoot(fromDirectory),
         System.IO.Path.GetPathRoot(toPath), true) != 0)
         {
             throw new ArgumentException(
             string.Format("The paths '{0} and '{1}' have different path roots.",
             fromDirectory, toPath));
         }
     }
     StringCollection relativePath = new StringCollection();
     string[] fromDirectories = fromDirectory.Split(System.IO.Path.DirectorySeparatorChar);
     string[] toDirectories = toPath.Split(System.IO.Path.DirectorySeparatorChar);
     int length = Math.Min(fromDirectories.Length, toDirectories.Length);
     int lastCommonRoot = -1;
     // find common root
     for(int x = 0; x < length; x++)
     {
         if(string.Compare(fromDirectories[x], toDirectories[x], true) != 0)
             break;
         lastCommonRoot = x;
     }
     if(lastCommonRoot == -1)
     {
         throw new ArgumentException(
         string.Format("The paths '{0} and '{1}' do not have a common prefix path.",
         fromDirectory, toPath));
     }
     // add relative folders in from path
     for(int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
         if(fromDirectories[x].Length > 0)
             relativePath.Add("..");
     // add to folders to path
     for(int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
         relativePath.Add(toDirectories[x]);
     // create relative path
     string[] relativeParts = new string[relativePath.Count];
     relativePath.CopyTo(relativeParts, 0);
     string newPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), relativeParts);
     return newPath;
 }
 private static void GetAllAssembly(Assembly assembly, StringCollection stringCollection)
 {
     string location = assembly.Location;
     if (!stringCollection.Contains(location))
     {
         stringCollection.Add(location);
     }
 }
 private NameValueListType GetSingleItemSpecific(string key, string value)
 {
     NameValueListType nv1 = new NameValueListType();
     nv1.Name = key;
     StringCollection nv1Col = new StringCollection();
     nv1Col.Add(value);
     nv1.Value = nv1Col;
     return nv1;
 }
Esempio n. 12
0
  protected void Page_Load(object sender, EventArgs e)
  {
    Configuration config = AppContext.GetConfiguration();

    if (Request.QueryString["check"] != null)
    {
      string status = "unknown";

      switch (Request.QueryString["check"].ToLower())
      {
        case "app":
          status = AppSettings.AppIsAvailable ? "up" : "down";
          break;

        case "appmessage":
          status = AppSettings.AppStatusMessage;
          break;

        case "mapservices":
          StringCollection serviceStatus = new StringCollection();

          foreach (Configuration.MapTabRow mapTab in config.MapTab)
          {
            bool isAvailable = AppContext.GetDataFrame(mapTab.MapTabID).Service.IsAvailable;
            serviceStatus.Add(mapTab.MapTabID + ": " + (isAvailable ? "up" : "down"));
          }

          status = serviceStatus.Join("; ");
          break;
      }

      Response.Write(status);
      Response.End();
    }

    labMessage.Text = AppSettings.AppStatusMessage;

    if (AppSettings.AppIsAvailable)
    {
      DataTable table = config.MapTab.Copy();
      table.Columns.Add("Status", typeof(string));

      foreach (DataRow row in table.Rows)
      {
        CommonDataFrame dataFrame = AppContext.GetDataFrame(row["MapTabID"].ToString());
        row["Status"] = dataFrame.Service.IsAvailable ? "up" : "down";
      }

      grdMapServices.DataSource = table;
      grdMapServices.DataBind();
      grdMapServices.Visible = true;
    }
  }
		private void getCatList(int number,ref StringCollection catList,out CategoryTypeCollection categories)
		{
			bool isSuccess;
			string message;

			catList.Clear();
			//get a leaf category
			isSuccess=CategoryHelper.GetCISSupportLeafCategory(number,out categories,this.apiContext,out message);
			Assert.IsTrue(isSuccess,message);
			for(int i=0;i<number;i++)
			{
				//add to catList
				catList.Add(categories[i].CategoryID);
			}
		}
Esempio n. 14
0
  } //AddName()

  public StringCollection GetNames() {
    // Assert FileIOPermission, caller may not have it!
    new FileIOPermission(PermissionState.Unrestricted).Assert();

    FileStream fs = new FileStream("names.txt", FileMode.Open,FileAccess.ReadWrite);
    StreamReader sr = new StreamReader(fs);
    StringCollection sc = new StringCollection();
    string s = sr.ReadLine();
    while (s != null) {
      sc.Add(s);
      s = sr.ReadLine();
    } //while
    fs.Close();
    return sc;
  } //GetNames()
 static void Main(string[] args)
 {
     if (args.Length != 2)
         Environment.Exit(1);
     string ip = args[0];
        	string hostname = args[1];
     try {
         String hosts = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\drivers\etc\hosts");
         string[] lines = File.ReadAllLines(hosts);
         StringCollection linesToSave = new StringCollection();
         foreach (string l in lines) {
             if (!l.Contains(hostname) && !l.Contains(ip)) {
                 linesToSave.Add(l);
             }
         }
         if (!".".Equals(ip))
             linesToSave.Add(ip + "\t" + hostname);
         lines = new String[linesToSave.Count];
         linesToSave.CopyTo(lines, 0);
         File.WriteAllLines(hosts, lines);
     } catch (Exception e) {
                 Console.WriteLine("{0}", e);
         }
 }
 public void GetContextualKeywords()
 {
     GetContextualKeywordsCall api = new GetContextualKeywordsCall(
     this.apiContext);
     // Make API call.
     ApiException gotException = null;
     StringCollection strings = new StringCollection();
     // Negative test.
     try {
         strings.Add("KeywordString");
     api.GetContextualKeywords("http://www.ebay.com", "ISO-8859-1", strings);
     } catch (ApiException ex) {
         gotException = ex;
     }
     Assert.IsNotNull(gotException);
 }
Esempio n. 17
0
 public void Put([FromBody]List<SelectOption> pingServices, string action = "")
 {
     var sc = new StringCollection();
     try
     {
         foreach (var item in pingServices)
         {
             sc.Add(item.OptionValue);
         }
         BlogService.SavePingServices(sc);
     }
     catch (System.Exception)
     {
         throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
     }
 }
 public void GetPopularKeywords()
 {
     GetPopularKeywordsCall api = new GetPopularKeywordsCall(this.apiContext);
     // Pagination
     PaginationType pt = new PaginationType();
     pt.EntriesPerPage = 50; pt.EntriesPerPageSpecified = true;
     pt.PageNumber = 1; pt.PageNumberSpecified = true;
     api.Pagination = pt;
     api.MaxKeywordsRetrieved = 100;
     StringCollection catIdList = new StringCollection();
     catIdList.Add("-1");
     api.CategoryIDList = catIdList;
     // Make API call
     api.Execute();
     CategoryTypeCollection words = api.ApiResponse.CategoryArray;
     Assert.IsTrue(words.Count > 0, "No keywords found");
     Boolean hasMore = api.ApiResponse.HasMore;
 }
		public void AddToWatchListFull()
		{
			watchListItem =	AddItem();
			Assert.IsNotNull(watchListItem, "Failed because failed to add item");
			Assert.AreNotEqual(watchListItem.ItemID,string.Empty);

			TestData.WatchedItem = watchListItem;
			AddToWatchListCall api = new AddToWatchListCall(this.apiContext);
			// Watch the first one.
			StringCollection ids = new StringCollection(); 
			ids.Add (watchListItem.ItemID);
			// Make API call.
			int num = api.AddToWatchList(ids, null);
			//check whether the call is success.
			Assert.IsTrue(api.ApiResponse.Ack==AckCodeType.Success || api.ApiResponse.Ack==AckCodeType.Warning,"do not success!");
			Assert.Greater(num,0);
			Assert.Greater(api.ApiResponse.WatchListCount,0);
			Assert.Greater(api.ApiResponse.WatchListMaximum,0);
		}
Esempio n. 20
0
        //***************************************************************************
        // Public Methods
        // 
        public string GetList()
        {
            int longLen = 0;
            StringCollection strCol = new StringCollection();
            string[] lns = this.txtItems.Text.Split(new char[] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < lns.Length; i++)
            {
                if (chkDistinct.Checked)
                    strCol.AddUnique(lns[i]);
                else
                    strCol.Add(lns[i]);
                longLen = (int)System.Math.Max(longLen, lns[i].Length);
            }

            string retVal = "";
            lns = strCol.ToArray();
            for (int i = 0; i < lns.Length; i++)
            {
                string newVal = string.Format("{2}{3}{1}{0}{1}{4}",
                                        lns[i],
                                        (this.chkQuotes.Checked)
                                                ? "'"
                                                : "",
                                        (i > 0) ? "," : "",
                                        (this.chkCheckSpace.Checked)
                                                ? ((i > 0) ? " " : "")
                                                : "",
                                        (this.numLnBreak.Value > 0 && ((i + 1) % (int)numLnBreak.Value == 0))
                                                ? "\n"
                                                : "");
                if (this.chkAlign.Checked)
                    newVal = newVal.PadLeft(longLen + ((this.chkCheckSpace.Checked) ? 1 : 0) + ((this.chkQuotes.Checked) ? 2 : 0) + ((this.numLnBreak.Value > 0 && ((i + 1) % (int)numLnBreak.Value == 0)) ? 1 : 0) + 1, ' ');
                retVal += newVal;
            }

            return retVal.TrimEnd(',', '\n');
        }
        public void SetPromotionalSaleListings()
        {
            SetPromotionalSaleListingsCall api = new SetPromotionalSaleListingsCall(this.apiContext);
            ItemIDArrayType itemIDArrayType = new ItemIDArrayType();
            StringCollection strCollection = new StringCollection();
            strCollection.Add("445566778L");
            itemIDArrayType.ItemID = strCollection;
            try
            {
                //add a param 'false' at the end by william, 3.13.2008
                PromotionalSaleStatusCodeType resp =
                    api.SetPromotionalSaleListings(16771004L, ModifyActionCodeType.Add,
                                                   itemIDArrayType, 234567890L, 12345L, true, false, false);

            }
            catch(ApiException apie)
            {
                Console.WriteLine("ApiException: " + apie.Message);
            }
            catch(SdkException sdke)
            {
                Assert.Fail("SdkException: " + sdke.Message);
            }
        }
Esempio n. 22
0
        private string CreateTempTables(string VariableName, string VariableNumber, bool makeGroupFactorCol)
        {
            // Get the name of the current method.
            string currentMethod = MethodBase.GetCurrentMethod().Name;

            //TODO; FIX
            string UniqueNumber = mSqlCommand.getUniqueNumber(7 + VariableNumber.Length);
            string tempTabellId;

            tempTabellId = "A" + UniqueNumber + "_TMP" + VariableNumber;

            if (DB.UseTemporaryTables)
            {
                tempTabellId = mSqlCommand.getPrefixIndicatingTempTable() + tempTabellId;
            }

            dropTheseTables.Add(tempTabellId);


            //----
            log.Debug("tempTabellId:" + tempTabellId + "        tempTabellId len:" + tempTabellId.Length);
            //
            // ORIGINALLY:
            // CREATE /***SQLID: CreateTempTables_01 ***/ TABLE A317838TEMP1
            // (AVariabel VARCHAR2(20), Group1 VARCHAR2(20), GroupNr1 NUMBER(5,0)
            // , GroupFactor1 NUMBER(5,0)
            // )
            //
            // 11.11.2008 ThH: CHANGED TO:
            // CREATE /***SQLID: CreateTempTables_01 ***/ TABLE A317838TEMP1
            // (AVariabel VARCHAR(20), Group1 VARCHAR(20), GroupNr1 INTEGER
            // , GroupFactor1 INTEGER
            // )
            // if (DB.database.Connection.useTemporaryTables) {
            string sqlString = "CREATE /*** SQLID: " + currentMethod + "_01 ***/";

            if (DB.UseTemporaryTables)
            {
                sqlString = sqlString + mSqlCommand.getKeywordAfterCreateIndicatingTempTable();
            }

            sqlString += " TABLE " + tempTabellId;

            // TODO; Mixed database/server instance         "(A" + VariableName + " VARCHAR(20), Group" + VariableNumber + " VARCHAR(20), GroupNr" + VariableNumber + " INTEGER";
            // TODO; this should not bed hardcoded -Just for test. Maybe should put element "tempCollation" in sqldbconfig.
            if ((DB.MainLanguage.code == "sv" || DB.Database.id == "FAO") && (DB.Database.Connection.dataProvider.ToString() == "Sql"))
            {
                sqlString += " (A" + VariableName + " VARCHAR(20) collate Finnish_Swedish_CI_AS, Group" + VariableNumber + " VARCHAR(20) collate Finnish_Swedish_CI_AS, GroupNr" + VariableNumber + " INTEGER";
            }
            else
            {
                sqlString += "(A" + VariableName + " VARCHAR(20), Group" + VariableNumber + " VARCHAR(20), GroupNr" + VariableNumber + " INTEGER";
            }
            if (makeGroupFactorCol)
            {
                sqlString += ", GroupFactor" + VariableNumber + " INTEGER";
            }
            sqlString += ")";

            if (DB.UseTemporaryTables)
            {
                sqlString = sqlString + mSqlCommand.getTempTableCreateCommandEndClause();
            }

            mSqlCommand.ExecuteNonQuery(sqlString);
            return(tempTabellId);
        }
Esempio n. 23
0
        private void GetForestTrustInfoHelper()
        {
            IntPtr             forestTrustInfo = (IntPtr)0;
            PolicySafeHandle   handle          = null;
            LSA_UNICODE_STRING tmpName         = null;
            bool   impersonated = false;
            IntPtr targetPtr    = (IntPtr)0;
            string serverName   = null;

            TopLevelNameCollection          tmpTLNs              = new TopLevelNameCollection();
            StringCollection                tmpExcludedTLNs      = new StringCollection();
            ForestTrustDomainInfoCollection tmpDomainInformation = new ForestTrustDomainInfoCollection();

            // internal members
            ArrayList tmpBinaryData       = new ArrayList();
            Hashtable tmpExcludedNameTime = new Hashtable();
            ArrayList tmpBinaryDataTime   = new ArrayList();

            try
            {
                try
                {
                    // get the target name
                    tmpName   = new LSA_UNICODE_STRING();
                    targetPtr = Marshal.StringToHGlobalUni(TargetName);
                    UnsafeNativeMethods.RtlInitUnicodeString(tmpName, targetPtr);

                    serverName = Utils.GetPolicyServerName(context, true, false, source);

                    // do impersonation
                    impersonated = Utils.Impersonate(context);

                    // get the policy handle
                    handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));

                    int result = UnsafeNativeMethods.LsaQueryForestTrustInformation(handle, tmpName, ref forestTrustInfo);
                    // check the result
                    if (result != 0)
                    {
                        int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
                        if (win32Error != 0)
                        {
                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
                        }
                    }

                    try
                    {
                        if (forestTrustInfo != (IntPtr)0)
                        {
                            LSA_FOREST_TRUST_INFORMATION trustInfo = new LSA_FOREST_TRUST_INFORMATION();
                            Marshal.PtrToStructure(forestTrustInfo, trustInfo);

                            int    count = trustInfo.RecordCount;
                            IntPtr addr  = (IntPtr)0;
                            for (int i = 0; i < count; i++)
                            {
                                addr = Marshal.ReadIntPtr(trustInfo.Entries, i * IntPtr.Size);
                                LSA_FOREST_TRUST_RECORD record = new LSA_FOREST_TRUST_RECORD();
                                Marshal.PtrToStructure(addr, record);

                                if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName)
                                {
                                    IntPtr myPtr = IntPtr.Add(addr, 16);
                                    Marshal.PtrToStructure(myPtr, record.TopLevelName);
                                    TopLevelName TLN = new TopLevelName(record.Flags, record.TopLevelName, record.Time);
                                    tmpTLNs.Add(TLN);
                                }
                                else if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelNameEx)
                                {
                                    // get the excluded TLN and put it in our collection
                                    IntPtr myPtr = IntPtr.Add(addr, 16);
                                    Marshal.PtrToStructure(myPtr, record.TopLevelName);
                                    string excludedName = Marshal.PtrToStringUni(record.TopLevelName.Buffer, record.TopLevelName.Length / 2);
                                    tmpExcludedTLNs.Add(excludedName);
                                    tmpExcludedNameTime.Add(excludedName, record.Time);
                                }
                                else if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustDomainInfo)
                                {
                                    ForestTrustDomainInformation dom = new ForestTrustDomainInformation(record.Flags, record.DomainInfo, record.Time);
                                    tmpDomainInformation.Add(dom);
                                }
                                else if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustRecordTypeLast)
                                {
                                    // enumeration is done, but we might still have some unrecognized entries after that
                                    continue;
                                }
                                else
                                {
                                    int    length    = record.Data.Length;
                                    byte[] byteArray = new byte[length];
                                    if ((record.Data.Buffer != (IntPtr)0) && (length != 0))
                                    {
                                        Marshal.Copy(record.Data.Buffer, byteArray, 0, length);
                                    }
                                    tmpBinaryData.Add(byteArray);
                                    tmpBinaryDataTime.Add(record.Time);
                                }
                            }
                        }
                    }
                    finally
                    {
                        UnsafeNativeMethods.LsaFreeMemory(forestTrustInfo);
                    }

                    _topLevelNames = tmpTLNs;
                    _excludedNames = tmpExcludedTLNs;
                    _domainInfo    = tmpDomainInformation;

                    _binaryData       = tmpBinaryData;
                    _excludedNameTime = tmpExcludedNameTime;
                    _binaryDataTime   = tmpBinaryDataTime;

                    // mark it as retrieved
                    retrieved = true;
                }
                finally
                {
                    if (impersonated)
                    {
                        Utils.Revert();
                    }

                    if (targetPtr != (IntPtr)0)
                    {
                        Marshal.FreeHGlobal(targetPtr);
                    }
                }
            }
            catch { throw; }
        }
Esempio n. 24
0
        /// <summary>
        /// Executes the script block.
        /// </summary>
        protected override void ExecuteTask()
        {
            // create compiler info for user-specified language
            CompilerInfo compilerInfo = CreateCompilerInfo(Language);

            // ensure base directory is set, even if fileset was not initialized
            // from XML
            if (References.BaseDirectory == null)
            {
                References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            ICodeCompiler      compiler = compilerInfo.Compiler;
            CompilerParameters options  = new CompilerParameters();

            options.GenerateExecutable = false;
            options.GenerateInMemory   = true;
            options.MainClass          = MainClass;

            // implicitly reference the NAnt.Core assembly
            options.ReferencedAssemblies.Add(typeof(Project).Assembly.Location);

            // Log the assembly being added to the CompilerParameters
            Log(Level.Verbose, "Adding assembly {0}", typeof(Project).Assembly.GetName().Name);

            // add (and load) assemblies specified by user
            foreach (string assemblyFile in References.FileNames)
            {
                try {
                    // load the assembly into current AppDomain to ensure it is
                    // available when executing the emitted assembly
                    Assembly asm = Assembly.LoadFrom(assemblyFile);

                    // Log the assembly being added to the CompilerParameters
                    Log(Level.Verbose, "Adding assembly {0}", asm.GetName().Name);

                    // add the location of the loaded assembly
                    if (!StringUtils.IsNullOrEmpty(asm.Location))
                    {
                        options.ReferencedAssemblies.Add(asm.Location);
                    }
                } catch (Exception ex) {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA2028"), assemblyFile), Location, ex);
                }
            }

            StringCollection imports = new StringCollection();

            foreach (NamespaceImport import in Imports)
            {
                if (import.IfDefined && !import.UnlessDefined)
                {
                    imports.Add(import.Namespace);
                }
            }

            // generate the code
            CodeCompileUnit compileUnit = compilerInfo.GenerateCode(_rootClassName,
                                                                    Code.Xml.InnerText, imports, Prefix);

            StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);

            compilerInfo.CodeGen.GenerateCodeFromCompileUnit(compileUnit, sw, null);
            string code = sw.ToString();

            Log(Level.Debug, ResourceUtils.GetString("String_GeneratedCodeLooksLike") + "\n{0}", code);

            CompilerResults results = compiler.CompileAssemblyFromDom(options, compileUnit);

            Assembly compiled = null;

            if (results.Errors.Count > 0)
            {
                string errors = ResourceUtils.GetString("NA2029") + Environment.NewLine;
                foreach (CompilerError err in results.Errors)
                {
                    errors += err.ToString() + Environment.NewLine;
                }
                errors += code;
                throw new BuildException(errors, Location);
            }
            else
            {
                compiled = results.CompiledAssembly;
            }

            // scan the new assembly for tasks, types and functions
            // Its unlikely that tasks will be defined in buildfiles though.
            bool extensionAssembly = TypeFactory.ScanAssembly(compiled, this);

            string mainClass = _rootClassName;

            if (!StringUtils.IsNullOrEmpty(MainClass))
            {
                mainClass += "+" + MainClass;
            }

            Type mainType = compiled.GetType(mainClass);

            if (mainType == null)
            {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       ResourceUtils.GetString("NA2030"), mainClass), Location);
            }

            MethodInfo entry = mainType.GetMethod("ScriptMain");

            // check for task or function definitions.
            if (entry == null)
            {
                if (!extensionAssembly)
                {
                    throw new BuildException(ResourceUtils.GetString("NA2031"), Location);
                }
                else
                {
                    return; // no entry point so nothing to do here beyond loading task and function defs
                }
            }

            if (!entry.IsStatic)
            {
                throw new BuildException(ResourceUtils.GetString("NA2032"), Location);
            }

            ParameterInfo[] entryParams = entry.GetParameters();

            if (entryParams.Length != 1)
            {
                throw new BuildException(ResourceUtils.GetString("NA2033"), Location);
            }

            if (entryParams[0].ParameterType.FullName != typeof(Project).FullName)
            {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       ResourceUtils.GetString("NA2034"), entryParams[0].ParameterType.FullName,
                                                       typeof(Project).FullName), Location);
            }

            try {
                // invoke Main method
                entry.Invoke(null, new object[] { Project });
            } catch (Exception ex) {
                // this exception is not likely to tell us much, BUT the
                // InnerException normally contains the runtime exception
                // thrown by the executed script code.
                throw new BuildException(ResourceUtils.GetString("NA2035"), Location,
                                         ex.InnerException);
            }
        }
Esempio n. 25
0
        private void SampleCutomization()
        {
            ToolTip1.SetToolTip(this.comboBoxAdv2, "WrapGrid option is only for Left,Right,Up,Down,PageUp,PageDown");

            //String collections...

            StringCollection ar = new StringCollection();

            ar.Add("None");
            ar.Add("Left");
            ar.Add("Right");
            ar.Add("Up");
            ar.Add("Down");
            ar.Add("Top");
            ar.Add("Bottom");
            ar.Add("MostLeft");
            ar.Add("MostRight");
            ar.Add("TopLeft");
            ar.Add("BottomRight");
            ar.Add("PageUp");
            ar.Add("PageDown");
            comboBoxAdv1.DataSource = ar;

            StringCollection ad = new StringCollection();

            ad.Add("None");
            ad.Add("WrapGrid");
            comboBoxAdv2.DataSource = ad;
            this.MetroColor         = System.Drawing.Color.Transparent;
            //Events
            this.comboBoxAdv1.SelectedIndexChanged  += new EventHandler(comboBoxAdv1_SelectedIndexChanged);
            this.comboBoxAdv2.SelectedIndexChanged  += new EventHandler(comboBoxAdv2_SelectedIndexChanged);
            this.formatCellsToolStripMenuItem.Click += new System.EventHandler(this.formatCellsToolStripMenuItem_Click);
        }
Esempio n. 26
0
		/// <summary>
		/// get a number of CatalogEnabled Categories.
		/// </summary>
		/// <param name="number"></param>
		/// <param name="apiContext"></param>
		/// <param name="categories"></param>
		/// <param name="message"></param>
		/// <returns></returns>
        //private static bool getCatagoryEnabledCategory(int number,ApiContext apiContext,CategoryEnableCodeType enableType,out CategoryTypeCollection categories,out string message)
        //{
        //    CategoryTypeCollection categoryTypeCollection;
        //    categories=new CategoryTypeCollection();
        //    bool isSuccess,isCatalogEnable;

        //    if(number<=0)
        //    {
        //        number=1;
        //    }

        //    if(getAllCategories(apiContext,out categoryTypeCollection,out message))
        //    {
        //        foreach(CategoryType category in categoryTypeCollection)
        //        {
        //            if(category.LeafCategory)
        //            {
        //                isSuccess = isCatagoryEnabled(apiContext,category.CategoryID,enableType,out isCatalogEnable,out message);
        //                if(isSuccess)
        //                {

        //                    if(isCatalogEnable)
        //                    {
        //                        categories.Add(category);
        //                    }

        //                    if(categories.Count>=number)
        //                    {
        //                        return true;
        //                    }
        //                }
        //                else
        //                {
        //                    message=message+";get features failure!";
        //                    return false;
        //                }
        //            }
        //        }//end foreach

        //        return true;
        //    }

        //    return false;
        //}
		
		/// <summary>
		/// check an category whether it is catalog-enabled.
		/// </summary>
		/// <param name="apiContext"></param>
		/// <param name="categorid"></param>
		/// <param name="isCatalogEnable"></param>
		/// <param name="message"></param>
		/// <returns></returns>
        //private static bool isCatagoryEnabled(ApiContext apiContext,string categorid,CategoryEnableCodeType enableType,out bool isEnable,out string message)
        //{
        //    CategoryTypeCollection categories;
        //    isEnable=false;
        //    message=string.Empty;

        //    GetCategory2CSCall api =new GetCategory2CSCall(apiContext);
        //    //GetCategoryFeaturesCall api = new GetCategoryFeaturesCall(apiContext);
        //    DetailLevelCodeType detaillevel= DetailLevelCodeType.ReturnAll;
        //    api.DetailLevelList=new DetailLevelCodeTypeCollection(new DetailLevelCodeType[]{detaillevel});
        //    api.CategoryID=categorid;
        //    try
        //    {
        //        categories = api.GetCategoryFeatures();
        //        foreach(CategoryType category in categories)
        //        {
        //            if(string.Compare(category.CategoryID,categorid,false)==0)
        //            {
        //                if(enableType==CategoryEnableCodeType.CatalogEnabled)
        //                {
        //                    isEnable=category.CatalogEnabled;
        //                    break;
        //                }
        //                else if(enableType==CategoryEnableCodeType.ProductSearchPageAvailable)
        //                {
        //                    isEnable=category.ProductSearchPageAvailable;
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //    catch(Exception e)
        //    {
        //        message=e.Message;
        //        return false;
        //    }
			
        //    return true;
        //}

		
		/// <summary>
		/// check whether a category id is valid.
		/// </summary>
		/// <param name="apiContext"></param>
		/// <param name="isValid"></param>
		/// <param name="message"></param>
		/// <returns></returns>
		private static bool isValidCategory(ApiContext apiContext,ref string categoryID,out bool isValid,out string message)
		{
			CategoryTypeCollection categories=null;
			message=string.Empty;
			isValid=false;

			GetCategoriesCall api=new GetCategoriesCall(apiContext);
			setBasicInfo(ref api);
			StringCollection parents=new StringCollection();
			parents.Add(categoryID);
			api.CategoryParent=parents;
			
			try
			{
				categories=api.GetCategories();

				if(categories!=null&&categories.Count>0)
				{
					foreach(CategoryType category in categories)
					{
						if(string.Compare(category.CategoryID,categoryID,true)==0)
						{
							isValid=true;
							break;
						}
					}
				}
			}
			catch(Exception e)
			{
				message=e.Message;
				return false;
			}

			return true;
		}
Esempio n. 27
0
        /// <summary>
        /// If extensions not in the cache will load
        ///     from the XML file. If file not exists
        ///     will load from assembly using reflection
        /// </summary>
        private static void LoadExtensions()
        {
            if (HttpRuntime.Cache["Extensions"] != null &&
                ((Dictionary <string, ManagedExtension>)HttpRuntime.Cache["Extensions"]).Count != 0)
            {
                return;
            }

            var codeAssemblies = Utils.CodeAssemblies();

            var meta = DataStoreExtension("MetaExtension");

            if (meta == null)
            {
                extensions.Add("MetaExtension", new ManagedExtension("MetaExtension", "1.0", "Meta extension", "BlogEngine.net"));
            }
            else
            {
                if (!extensions.ContainsKey("MetaExtension"))
                {
                    extensions.Add("MetaExtension", meta);
                }
            }

            foreach (Assembly a in codeAssemblies)
            {
                var types = a.GetTypes();
                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes(typeof(ExtensionAttribute), false);
                    foreach (var xa in attributes.Cast <ExtensionAttribute>())
                    {
                        // try to load from storage
                        try
                        {
                            var x = DataStoreExtension(type.Name);

                            // if nothing, crete new extension
                            if (x == null)
                            {
                                x = new ManagedExtension(type.Name, xa.Version, xa.Description, xa.Author);
                                newExtensions.Add(type.Name);
                                SaveToStorage(x);
                            }
                            else
                            {
                                // update attributes from assembly
                                x.Version     = xa.Version;
                                x.Description = xa.Description;
                                x.Author      = xa.Author;

                                if (x.Priority == 0)
                                {
                                    x.Priority = xa.Priority;
                                }

                                if (!x.SubBlogEnabled)
                                {
                                    x.SubBlogEnabled = xa.SubBlogEnabled;
                                }
                            }
                            if (!extensions.ContainsKey(x.Name))
                            {
                                extensions.Add(x.Name, x);
                            }
                        }
                        catch (Exception e)
                        {
                            Utils.Log($"Can not load {type.Name}: {e.Message}");
                        }
                    }
                }
            }

            // SaveToStorage();
            SaveToCache();
        }
Esempio n. 28
0
        void FileStatusListView_MouseMove(object sender, MouseEventArgs e)
        {
            ListView listView = sender as ListView;

            //DRAG
            // If the mouse moves outside the rectangle, start the drag.
            if (dragBoxFromMouseDown != Rectangle.Empty &&
                !dragBoxFromMouseDown.Contains(e.X, e.Y))
            {
                if (SelectedItems.Any())
                {
                    StringCollection fileList = new StringCollection();

                    foreach (GitItemStatus item in SelectedItems)
                    {
                        string fileName = Path.Combine(Module.WorkingDir, item.Name);

                        fileList.Add(fileName.ToNativePath());
                    }

                    DataObject obj = new DataObject();
                    obj.SetFileDropList(fileList);

                    // Proceed with the drag and drop, passing in the list item.
                    DoDragDrop(obj, DragDropEffects.Copy);
                    dragBoxFromMouseDown = Rectangle.Empty;
                }
            }

            //TOOLTIP
            if (listView != null)
            {
                ListViewItem hoveredItem;
                try
                {
                    var point = new Point(e.X, e.Y);
                    hoveredItem = listView.HitTest(point).Item;
                }
                catch (ArgumentOutOfRangeException)
                {
                    hoveredItem = null;
                }
                if (hoveredItem != null)
                {
                    var gitItemStatus = (GitItemStatus)hoveredItem.Tag;

                    string text;
                    if (gitItemStatus.IsRenamed || gitItemStatus.IsCopied)
                    {
                        text = string.Concat(gitItemStatus.Name, " (", gitItemStatus.OldName, ")");
                    }
                    else
                    {
                        text = gitItemStatus.Name;
                    }

                    float fTextWidth = listView.CreateGraphics().MeasureString(text, listView.Font).Width + 17;

                    //Use width-itemheight because the icon drawn in front of the text is the itemheight
                    if (fTextWidth > (FileStatusListView.Width - FileStatusListView.GetItemRect(hoveredItem.Index).Height))
                    {
                        if (!hoveredItem.ToolTipText.Equals(gitItemStatus.ToString()))
                        {
                            hoveredItem.ToolTipText = gitItemStatus.ToString();
                        }
                    }
                    else
                    {
                        hoveredItem.ToolTipText = "";
                    }
                }
            }
        }
Esempio n. 29
0
    // Main entry point for the application.
    public static int Main(String[] args)
    {
#if CONFIG_EXTENDED_NUMERICS && CONFIG_REFLECTION
        StreamReader     reader = null;
        int              len;
        VsaEngine        engine;
        IVsaCodeItem     item;
        StringCollection scripts = new StringCollection();

        // Create an engine instance and add the script to it.
        engine = VsaEngine.CreateEngine();
        engine.SetOption("print", true);

        // get command-line arguments
        int    i   = 0;
        String arg = args.Length == 0 ? null : args[0];
        while (arg != null)
        {
            String next = null;
            if (arg.StartsWith("-") && !arg.StartsWith("--") &&
                arg.Length > 2)
            {
                next = "-" + arg.Substring(2, arg.Length - 2);
                arg  = arg.Substring(0, 2);
            }
            switch (arg)
            {
            case "-h":
            case "--help":
                Usage();
                return(0);

            case "-v":
            case "--version":
                Version();
                return(0);

            default:
                // matches both short and long options. (-/--)
                if (arg.StartsWith("-"))
                {
#if !CONFIG_SMALL_CONSOLE
                    Console.Error.WriteLine
#else
                    Console.WriteLine
#endif
                        ("jsrun: unkown option `{0}'", arg);

                    return(1);
                }
                // not an option - assumes script path
                else
                {
                    // To prevent a relative and a absolute pathname to same file!
                    FileInfo fi = new FileInfo(arg);
                    if (!fi.Exists)
                    {
#if !CONFIG_SMALL_CONSOLE
                        Console.Error.WriteLine
#else
                        Console.WriteLine
#endif
                            ("jsrun: {0}: No such file or directory", arg);

                        return(1);
                    }
                    // Cannot load same script source twice!
                    if (scripts.Contains(fi.FullName))
                    {
#if !CONFIG_SMALL_CONSOLE
                        Console.Error.WriteLine
#else
                        Console.WriteLine
#endif
                            ("jsrun: {0}: use of duplicate sources illegal.", fi.FullName);
                    }
                    else
                    {
                        scripts.Add(fi.FullName);
                    }
                    // Load script file
                    try
                    {
                        reader = new StreamReader(arg);
                    }
                    catch (Exception e)
                    {
#if !CONFIG_SMALL_CONSOLE
                        Console.Error.WriteLine
#else
                        Console.WriteLine
#endif
                            ("jsrun: ({0}): {1}", e.GetType(), e.Message);
                    }

                    // Load the script into memory as a string.
                    StringBuilder scriptBuilder = new StringBuilder();
                    char[]        scriptBuffer  = new char [512];
                    while ((len = reader.Read(scriptBuffer, 0, 512)) > 0)
                    {
                        scriptBuilder.Append(scriptBuffer, 0, len);
                    }
                    reader.Close();

                    item = (IVsaCodeItem)(engine.Items.CreateItem
                                              (String.Concat("script", engine.Items.Count + 1),
                                              VsaItemType.Code, VsaItemFlag.None));
                    item.SourceText = scriptBuilder.ToString();
                    item.SetOption("codebase", arg);
                }
                break;
            }                             // switch(arg)

            if (next != null)
            {
                arg = next;
            }
            else if (i + 1 >= args.Length)
            {
                arg = null;
            }
            else
            {
                i   = i + 1;
                arg = args[i];
            }
        }                         // for each in args

        // We need at least one item.
        if (engine.Items.Count == 0)
        {
            Usage();
            return(1);
        }

        // Compile and run the script.
        if (!engine.Compile())
        {
#if !CONFIG_SMALL_CONSOLE
            Console.Error.WriteLine
#else
            Console.WriteLine
#endif
                ("jsrun: Could not compile script");

            return(1);
        }
        engine.Run();

        // Shut down the engine and exit.
        engine.Close();
        return(0);
#else
        // Use error output and exit status in case any
        // script/program is depending on output.
#if !CONFIG_SMALL_CONSOLE
        Console.Error.WriteLine
#else
        Console.WriteLine
#endif
            ("JScript is not available in this configuration " +
            "because the library does\n" +
            "not have sufficient features to support JScript.");

        return(1);
#endif
    }
Esempio n. 30
0
        private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
        {
            StringCollection retVal = new StringCollection();

            if (string.IsNullOrEmpty(val))
            {
                // if null or empty, just add and we are done
                retVal.Add(val);
                return(retVal);
            }

            // break string on newlines and process each line separately
            string[] lines = SplitLines(val);

            for (int k = 0; k < lines.Length; k++)
            {
                if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen)
                {
                    // we do not need to split further, just add
                    retVal.Add(lines[k]);
                    continue;
                }

                int           spacesLeft = firstLineLen;
                int           lineWidth  = firstLineLen;
                bool          firstLine  = true;
                StringBuilder singleLine = new StringBuilder();

                foreach (GetWordsResult word in GetWords(lines[k]))
                {
                    string wordToAdd = word.Word;

                    // Handle soft hyphen
                    if (word.Delim == s_softHyphen.ToString())
                    {
                        int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(s_softHyphen.ToString());

                        // Add hyphen only if necessary
                        if (wordWidthWithHyphen == spacesLeft)
                        {
                            wordToAdd += "-";
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(word.Delim))
                        {
                            wordToAdd += word.Delim;
                        }
                    }

                    int wordWidth = displayCells.Length(wordToAdd);

                    // Handle zero width
                    if (lineWidth == 0)
                    {
                        if (firstLine)
                        {
                            firstLine = false;
                            lineWidth = followingLinesLen;
                        }

                        if (lineWidth == 0)
                        {
                            break;
                        }

                        spacesLeft = lineWidth;
                    }

                    // Word is wider than a single line
                    if (wordWidth > lineWidth)
                    {
                        foreach (char c in wordToAdd)
                        {
                            char charToAdd = c;
                            int  charWidth = displayCells.Length(c);

                            // corner case: we have a two cell character and the current
                            // display length is one.
                            // add a single cell arbitrary character instead of the original
                            // one and keep going
                            if (charWidth > lineWidth)
                            {
                                charToAdd = '?';
                                charWidth = 1;
                            }

                            if (charWidth > spacesLeft)
                            {
                                retVal.Add(singleLine.ToString());
                                singleLine.Clear();
                                singleLine.Append(charToAdd);

                                if (firstLine)
                                {
                                    firstLine = false;
                                    lineWidth = followingLinesLen;
                                }

                                spacesLeft = lineWidth - charWidth;
                            }
                            else
                            {
                                singleLine.Append(charToAdd);
                                spacesLeft -= charWidth;
                            }
                        }
                    }
                    else
                    {
                        if (wordWidth > spacesLeft)
                        {
                            retVal.Add(singleLine.ToString());
                            singleLine.Clear();
                            singleLine.Append(wordToAdd);

                            if (firstLine)
                            {
                                firstLine = false;
                                lineWidth = followingLinesLen;
                            }

                            spacesLeft = lineWidth - wordWidth;
                        }
                        else
                        {
                            singleLine.Append(wordToAdd);
                            spacesLeft -= wordWidth;
                        }
                    }
                }

                retVal.Add(singleLine.ToString());
            }

            return(retVal);
        }
Esempio n. 31
0
        private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen)
        {
            StringCollection retVal = new StringCollection();

            if (string.IsNullOrEmpty(val))
            {
                // if null or empty, just add and we are done
                retVal.Add(val);
                return(retVal);
            }

            // break string on newlines and process each line separately
            string[] lines = SplitLines(val);

            for (int k = 0; k < lines.Length; k++)
            {
                if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen)
                {
                    // we do not need to split further, just add
                    retVal.Add(lines[k]);
                    continue;
                }

                // the string does not fit, so we have to wrap around on multiple lines
                // for each of these lines in the string, the first line will have
                // a (potentially) different length (indentation or hanging)

                // for each line, start a new state
                SplitLinesAccumulator accumulator = new SplitLinesAccumulator(retVal, firstLineLen, followingLinesLen);

                int offset = 0; // offset into the line we are splitting

                while (true)
                {
                    // acquire the current active display line length (it can very from call to call)
                    int currentDisplayLen = accumulator.ActiveLen;

                    // determine if the current tail would fit or not

                    // for the remaining part of the string, determine its display cell count
                    int currentCellsToFit = displayCells.Length(lines[k], offset);

                    // determine if we fit into the line
                    int excessCells = currentCellsToFit - currentDisplayLen;

                    if (excessCells > 0)
                    {
                        // we are not at the end of the string, select a sub string
                        // that would fit in the remaining display length
                        int charactersToAdd = displayCells.GetHeadSplitLength(lines[k], offset, currentDisplayLen);

                        if (charactersToAdd <= 0)
                        {
                            // corner case: we have a two cell character and the current
                            // display length is one.
                            // add a single cell arbitrary character instead of the original
                            // one and keep going
                            charactersToAdd = 1;
                            accumulator.AddLine("?");
                        }
                        else
                        {
                            // of the given length, add it to the accumulator
                            accumulator.AddLine(lines[k].Substring(offset, charactersToAdd));
                        }

                        // increase the offset by the # of characters added
                        offset += charactersToAdd;
                    }
                    else
                    {
                        // we reached the last (partial) line, we add it all
                        accumulator.AddLine(lines[k].Substring(offset));
                        break;
                    }
                }
            }

            return(retVal);
        }
Esempio n. 32
0
        /// <summary>
        /// Returns a relative path between two directories.  Sourced from
        /// http://weblogs.asp.net/pwelter34/archive/2006/02/08/create-a-relative-path-code-snippet.aspx.
        /// </summary>
        /// <param name="fromDirectory">The from directory.</param>
        /// <param name="toPath">The to directory.</param>
        /// <returns>The relative path.</returns>
        public static string GetRelativePath(string fromDirectory, string toPath)
        {
            if (fromDirectory == null)
            {
                throw new ArgumentNullException("fromDirectory");
            }

            if (toPath == null)
            {
                throw new ArgumentNullException("toPath");
            }

            bool isRooted = Path.IsPathRooted(fromDirectory) &&
                            Path.IsPathRooted(toPath);

            if (isRooted)
            {
                bool isDifferentRoot = string.Compare(
                    Path.GetPathRoot(fromDirectory),
                    Path.GetPathRoot(toPath), true) != 0;

                if (isDifferentRoot)
                {
                    return(toPath);
                }
            }

            StringCollection relativePath = new StringCollection();

            string[] fromDirectories = fromDirectory.Split(
                Path.DirectorySeparatorChar);

            string[] toDirectories = toPath.Split(
                Path.DirectorySeparatorChar);

            int length = Math.Min(
                fromDirectories.Length,
                toDirectories.Length);

            int lastCommonRoot = -1;

            // find common root
            for (int x = 0; x < length; x++)
            {
                if (string.Compare(fromDirectories[x],
                                   toDirectories[x], true) != 0)
                {
                    break;
                }

                lastCommonRoot = x;
            }
            if (lastCommonRoot == -1)
            {
                return(toPath);
            }

            // add relative folders in from path
            for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
            {
                if (fromDirectories[x].Length > 0)
                {
                    relativePath.Add("..");
                }
            }

            // add to folders to path
            for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
            {
                relativePath.Add(toDirectories[x]);
            }

            // create relative path
            string[] relativeParts = new string[relativePath.Count];
            relativePath.CopyTo(relativeParts, 0);

            string newPath = string.Join(
                Path.DirectorySeparatorChar.ToString(),
                relativeParts);

            return(newPath);
        }
        private void SetTimeVal()
        {
            string timeUnit;

            if (mTimeScale.TimeUnit == meta.Config.Codes.TimeUnitA)
            {
                timeUnit = "A1";
            }
            else if (mTimeScale.TimeUnit == meta.Config.Codes.TimeUnitH)
            {
                timeUnit = "H1";
            }
            else if (mTimeScale.TimeUnit == meta.Config.Codes.TimeUnitM)
            {
                timeUnit = "M1";
            }
            else if (mTimeScale.TimeUnit == meta.Config.Codes.TimeUnitQ)
            {
                timeUnit = "Q1";
            }
            else if (mTimeScale.TimeUnit == meta.Config.Codes.TimeUnitW)
            {
                timeUnit = "W1";
            }
            else
            {
                log.InfoFormat("Unknown Timeunit:{0}", mTimeScale.TimeUnit);
                timeUnit = mTimeScale.TimeUnit;
            }

            mTimeVal = new StringCollection();
            mTimeVal.Add("TLIST(" + timeUnit + ")");
            mHasTimeVal = true;
            if (!meta.MainTable.ContainsOnlyMetaData)
            {
                string    lowestSelectedTime;
                string    highestSelectedTime;
                ArrayList selectedTimeCodes = new ArrayList();
                foreach (KeyValuePair <string, PXSqlValue> val in mValues)
                {
                    selectedTimeCodes.Add(val.Value.ValueCode);
                }
                selectedTimeCodes.Sort();
                lowestSelectedTime  = selectedTimeCodes[0].ToString();
                highestSelectedTime = selectedTimeCodes[selectedTimeCodes.Count - 1].ToString();
                ArrayList allTimeCodes       = TimeValueCodesSortedChronologicaly();
                int       startIndexAllTimes = allTimeCodes.IndexOf(lowestSelectedTime);
                int       endIndexAllTimes   = allTimeCodes.IndexOf(highestSelectedTime);
                for (int i = startIndexAllTimes; i <= endIndexAllTimes; i++)
                {
                    mTimeVal.Add(allTimeCodes[i].ToString());
                    if (!selectedTimeCodes.Contains(allTimeCodes[i]))
                    {
                        //TODO; Dette gjøres midlertidig for å sørge for at Timeval
                        //vises i serialiseringen
                        mTimeVal.Clear();
                        mTimeVal.Add("TLIST(" + timeUnit + ")");
                        break;
                    }
                }
            }
        }
Esempio n. 34
0
    protected void AddButton_Click(object sender, EventArgs e)
    {
        string interestedShares = "";

        //  foreach (ListItem share in StocksLB.Items)
        //foreach (ListItem stock in StocksCBL.Items)
        //{
        //    if (stock.Selected == true)
        //    {
        //        if (interestedShares != "")
        //        {
        //            interestedShares = interestedShares + "," + stock.Value;
        //        }
        //        else
        //        {
        //            interestedShares = stock.Value;
        //        }
        //    }
        //}

        int selectedItemsCount = 0;
        for (int n = 0; n < StocksCBL.Items.Count; n++)
        {
            if (StocksCBL.Items[n].Selected)
            {
                selectedItemsCount++;
                if (selectedItemsCount > maxStocksPerUser)
                {
                    break;
                }
            }
        }

        if (selectedItemsCount > maxStocksPerUser)
        {
            SaveChangesLabel.Text = "Currently Stoocker allows a maximum of " + gui.RedFontStart + maxStocksPerUser.ToString() + gui.RedFontEnd + " stocks per portfolio."
                + gui.LineBreak + "Please choose accordingly.";
        }
        else
        {

            string queryString = "INSERT IGNORE INTO stoocks.perstockexpertise VALUES ";
            StringCollection insertionValuesSC = new StringCollection();

            //  int defaultExpertise = 2;
            //  double defaultCurrentWeight = 100.0;

            int expertise = (int)ProcessingEngine.ExpertiseLevel.Intermediate;
            double userWeight = engine.InitialUserWeight;

            for (int i = 0; i < StocksCBL.Items.Count; i++)
            {
                if (StocksCBL.Items[i].Selected)
                {
                    if (interestedShares != "")
                    {
                        interestedShares = interestedShares + "," + StocksCBL.Items[i].Value;
                        insertionValuesSC.Add("('" + username + "', '" + StocksCBL.Items[i] + "', " + expertise + "," + userWeight + ") ");
                    }
                    else
                    {
                        interestedShares = StocksCBL.Items[i].Value;
                    }
                }
            }

            string insertionValuesString = "";
            for (int i = 0; i < insertionValuesSC.Count; i++)
            {
                if (i == (insertionValuesSC.Count - 1))
                {
                    insertionValuesString += insertionValuesSC[i] + ";";
                }
                else
                {
                    insertionValuesString += insertionValuesSC[i] + ",";
                }
            }

            //  Update perstockexpertise Table.
            queryString = queryString + insertionValuesString;
            int retVal = dbOps.ExecuteNonQuery(queryString);

            //  Response.Write("You Selected: " + interestedShares);
            //  System.Threading.Thread.Sleep(2000);

            interestedShares = SortAlphabetically(interestedShares);

            bool isUpdated = UpdateInterestsDB(username, interestedShares);
            if (isUpdated)
            {
                Response.Redirect(links.HomePageLink);
            }
        }
    }
Esempio n. 35
0
        private void Merge()
        {
            #region <Locals>
            string TEMP_FILE = "~gmlst~";
            string TEMP_DIR  = options.WorkingFolder + "~gmtdir~\\";
            char[] SLASH     = new char[] { '/' };
            char[] SPACE     = new char[] { ' ' };
            char[] ENDLINE   = new char[] { '\n', '\r' };
            char[] PIPE      = new char[] { '\xB3' };

            Regex            hackRE = new Regex("\\(([^\\)]+) (Hack|hack)\\)");
            string[]         splitText, split2;
            string[]         romExtensions = {};
            StringCollection files;

            FileInfo      fileStats = null;
            FileInfo      file      = null;
            StreamWriter  outputWriter;
            XmlDocument   xd;
            XmlNodeList   xnl;
            XmlTextReader xtr;
            LineParser    lp;

            long     pauseTime;
            DateTime opStart;

            int  loop;
            int  expectedCount = 0;
            int  actualCount   = 0;
            int  fileCount     = 0;
            int  archiveNumber = 1;
            long inputSizeBytes;
            long inputSize;
            long totalInputSize  = 0;
            long totalOutputSize = 0;
            bool matched;

            string curLine, fullOutput, lastFound, parent = "";
            string coArgStart, coArgMid, coArgEnd, deArgStart, deArgEnd, settings = "";
            string name, version;

            string decompressExe;
            string compressExe;
            if (options.SourceCompression == "rar")
            {
                decompressExe = options.Rar;
            }
            else if (options.SourceCompression == "ace")
            {
                decompressExe = options.Ace;
            }
            else
            {
                decompressExe = options.SevenZip;
            }
            if (options.OutputCompression == "rar")
            {
                compressExe = options.Rar;
            }
            else if (options.OutputCompression == "ace")
            {
                compressExe = options.Ace;
            }
            else
            {
                compressExe = options.SevenZip;
            }

            #endregion

            #region <Parse *.gmdb>

            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
             * / Read "*.gmdb" for information about clones.
             * / Format of the file is as follows:
             * /     <SET VER/ext[/ext...]>
             * /     Parent/Clone[/Clone...]
             * /     <BIAS/b1[[/b2][/b3...]]>
             * /     Parent1[[/Parent2][/Parent3...]][/Clone...]
             * /     <SET...
             * / There may be any number of clones listed, but at least one
             * / must appear for each parent in the first section. In the
             * / second section, each parent corresponds to the biases listed
             * / in order, thus there must be as many parents as biases. Any
             * / clone containing a '*' is a wild card match.
             * /
             * / Empty lines and those starting with ';' are ignored.
             * /
             * / Construct a hash table for explicit clones where the key is
             * / the clone name and the value is the associated parent.
             * / Construct a hash table for '*' clones where the key is the
             * / match text and the value is the associated parent.
             * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            // Find file with the correct ROMSet.
            matched = false;
            foreach (FileInfo f in new DirectoryInfo(options.ProgramFolder).GetFiles("*.xmdb"))
            {
                xtr = null;
                try {
                    xtr = new XmlTextReader(f.FullName);

                    // Check that the root node is <romsets>.
                    if (xtr.MoveToContent() == XmlNodeType.None || !xtr.Name.Equals("romsets"))
                    {
                        continue;
                    }

                    // Read each child <set> node.
                    xtr.Read();
                    while (xtr.MoveToContent() != XmlNodeType.None)
                    {
                        if (xtr.Name.Equals("set"))
                        {
                            name    = null;
                            version = null;
                            // Check that name="SetName" and version="Version".
                            while (xtr.MoveToNextAttribute())
                            {
                                if (xtr.Name.Equals("name"))
                                {
                                    name = xtr.Value;
                                }
                                else if (xtr.Name.Equals("version"))
                                {
                                    version = xtr.Value;
                                }
                            }
                            if (name != null && version != null && name.Equals(options.SetName) && version.Equals(options.Version))
                            {
                                matched = true;
                                break;
                            }
                        }
                        xtr.Skip();
                    }
                    if (matched)
                    {
                        file = f;
                        break;
                    }
                }
                catch { }
                finally { if (xtr != null)
                          {
                              xtr.Close();
                          }
                }
            }
            if (!matched)
            {
                doError(options.Strings[42] + " \"" + options.SetName + "\" (" + options.Strings[43] + " \"" + options.Version + "\") " + options.Strings[44]); return;
            }

            log.AppendText(options.Strings[45] + " \"" + file.FullName + "\"?", LogWindow.GoodColor);
            string n = "";

            // Attempt to load the document.
            xd = new XmlDocument();
            var readerSettings = new XmlReaderSettings {
                ProhibitDtd = false, ValidationType = ValidationType.DTD
            };
            var tempxvr = XmlReader.Create(file.FullName, readerSettings);
            try { xd.Load(tempxvr); }
            catch (Exception e) { doError("XML loading error.\n" + e.Message.Replace(" An error occurred at file:///", "\nFile: ").Replace(", (", "\nLine, Column: (")); return; }
            finally { tempxvr.Close(); }
            string root = "/romsets/set[@name=\"" + options.SetName + "\" and @version=\"" + options.Version + "\"]";
            xnl = xd.SelectNodes(root);

            // Parse the extensions.
            xnl = xd.SelectNodes(root + "/options/ext/@text");
            if (xnl.Count == 0)
            {
                doError(options.Strings[46] + options.Strings[47]); return;
            }
            romExtensions = new string[xnl.Count];
            for (loop = 0; loop < xnl.Count; loop++)
            {
                romExtensions[loop] = xnl[loop].Value;
            }

            // Parse the flags.
            xnl = xd.SelectNodes(root + "/options/flag/@reg");
            if (xnl.Count == 0)
            {
                doError(options.Strings[46] + options.Strings[48]); return;
            }
            Flags = new Regex[xnl.Count];
            for (loop = 0; loop < xnl.Count; loop++)
            {
                Flags[loop] = new Regex(xnl[loop].Value);
            }

            // Parse the hackflags, if present.
            xnl = xd.SelectNodes(root + "/options/hackflag/@reg");
            if (xnl.Count != 0)
            {
                HackFlags = new Regex[xnl.Count];
                for (loop = 0; loop < xnl.Count; loop++)
                {
                    HackFlags[loop] = new Regex(xnl[loop].Value);
                }
            }

            // Parse the ignores, if present.
            xnl = xd.SelectNodes(root + "/options/ignore/@reg");
            if (xnl.Count != 0)
            {
                Ignores = new Regex[xnl.Count];
                for (loop = 0; loop < xnl.Count; loop++)
                {
                    Ignores[loop] = new Regex(xnl[loop].Value);
                }
            }

            // Add all explicit parents.
            xnl = xd.SelectNodes(root + "/parents/parent");
            foreach (XmlNode xn in xnl)
            {
                parent = xn.Attributes["name"].Value;
                foreach (XmlNode child in xn.ChildNodes)
                {
                    if (child.NodeType == XmlNodeType.Element && child.Name == "clone")
                    {
                        AddClone(parent, child.Attributes["name"].Value);
                    }
                    else if (child.NodeType == XmlNodeType.Element && child.Name == "group")
                    {
                        wildCardClones.Add(new Regex(child.Attributes["reg"].Value), parent);
                    }
                }
            }

            // Add all zoned parents.
            xnl = xd.SelectNodes(root + "/parents/zoned");
            bool deferred;
            foreach (XmlNode xn in xnl)
            {
                XmlNodeList biasNodes = ((XmlElement)xn).GetElementsByTagName("bias");
                int         rank      = Int32.MaxValue;
                // Find the parent with the highest priority.
                foreach (XmlNode bias in biasNodes)
                {
                    if (!options.Biases.Contains(bias.Attributes["zone"].Value))
                    {
                        n = "\n";
                        if (options.TestMode)
                        {
                            log.AppendText(n + options.Strings[49] + bias.Attributes["zone"].Value, LogWindow.BadColor);
                        }
                    }
                    else if (options.Biases.IndexOf(bias.Attributes["zone"].Value) < rank)
                    {
                        parent = bias.Attributes["name"].Value;
                        rank   = options.Biases.IndexOf(bias.Attributes["zone"].Value);
                    }
                }
                if (rank == Int32.MaxValue)
                {
                    continue;
                }
                deferred = xn.Attributes["type"].Value.Equals("deferred");
                // Add all clones.
                foreach (XmlNode child in xn.ChildNodes)
                {
                    if (child.NodeType == XmlNodeType.Element && child.Name == "bias" && !deferred)
                    {
                        AddClone(parent, child.Attributes["name"].Value);
                    }
                    else if (child.NodeType == XmlNodeType.Element && child.Name == "clone")
                    {
                        AddClone(parent, child.Attributes["name"].Value);
                    }
                    else if (child.NodeType == XmlNodeType.Element && child.Name == "group")
                    {
                        wildCardClones.Add(new Regex(child.Attributes["reg"].Value), parent);
                    }
                }
            }

            log.AppendText(n + options.Strings[50] + "\n", LogWindow.GoodColor);

            #endregion
            #region <Parse Have.txt>

            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
             * / Read "XXXXHave.txt" for the list of the actual ROMs to be
             * / compressed. Sort them by the parent ROM's name. Note how many
             * / files should be compressed.
             * /
             * / Construct a hash table where the key is the parent name and
             * / the value is a list of clone names. To determine the parent,
             * / first check if the full name contains any of the '*' strings.
             * / If so, use the parent of the first matching string. Next,
             * / strip the flags off the full name and check if the result is
             * / present in the explicit clones table. If so, add this entry
             * / using the parent from that table. Otherwise, just use the
             * / flag-stripped name as the parent.
             * /
             * / Hacks are handled separately so that they can be checked
             * / against the names already in the hash table.
             * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            log.AppendText(options.Strings[45] + " \"" + options.HaveFile + "\"?", LogWindow.GoodColor);

            matched = false;
            lp      = new LineParser(options.HaveFile);

            // Get the expected count.
            curLine   = lp.GetNextLine();
            splitText = curLine.Split(SPACE);
            try { expectedCount = Int32.Parse(splitText[4]); }
            catch {
                try { expectedCount = Int32.Parse(splitText[3]); }
                catch { doError(options.Strings[51]); return; }
            }

            // Read each entry.
            curLine = lp.GetNextLine();
            while (curLine != null)
            {
                matched = false;

                // First, try to match against the wild cards.
                foreach (DictionaryEntry entry in wildCardClones)
                {
                    if (((Regex)(entry.Key)).Match(curLine).Success)
                    {
                        matched = true;
                        parent  = entry.Value.ToString();
                        break;
                    }
                }
                if (!matched)
                {
                    // If it's a hack, process it later.
                    if (hackRE.IsMatch(curLine))
                    {
                        Hacks.Add(curLine);
                    }
                    else
                    {
                        // Otherwise, do the flag strip dance.
                        parent = StripFlags(curLine);
                        if (explicitClones.Contains(parent))
                        {
                            parent = explicitClones[parent].ToString();
                        }
                        matched = true;
                    }
                }
                if (matched)   // Not a hack.
                {
                    if (ROMs.Contains(parent))
                    {
                        ((StringCollection)(ROMs[parent])).Add(curLine);
                    }
                    else
                    {
                        files = new StringCollection();
                        files.Add(curLine);
                        ROMs.Add(parent, files);
                    }
                }

                curLine = lp.GetNextLine();
            }

            // Now handle the hacks. Add the hack under the parent name that's
            // part of the filename if that name is already listed anywhere.
            // Otherwise, make a new entry with the flag stripped name.

            if (Hacks.Count != 0 && HackFlags != null)
            {
                foreach (DictionaryEntry de in ROMs)
                {
                    try { HackROMs.Add(StripHackFlags(de.Key.ToString()), de.Key); }
                    catch { }
                }
            }

            foreach (string str in Hacks)
            {
                string hackname = hackRE.Match(str).Groups[1].Value;
                if (explicitClones.Contains(hackname))
                {
                    parent = explicitClones[hackname].ToString();
                }
                else if (!HackROMs.Contains(hackname))
                {
                    parent = StripFlags(str);
                    if (explicitClones.Contains(parent))
                    {
                        parent = explicitClones[parent].ToString();
                    }
                }
                else
                {
                    parent = HackROMs[hackname].ToString();
                }
                if (ROMs.Contains(parent))
                {
                    ((StringCollection)(ROMs[parent])).Add(str);
                }
                else
                {
                    files = new StringCollection();
                    files.Add(str);
                    ROMs.Add(parent, files);
                }
            }

            log.AppendText(options.Strings[50] + "\n", LogWindow.GoodColor);
            log.AppendText(options.Strings[52], LogWindow.GoodColor);
            log.PopulateTree(ROMs);
            log.AppendText(options.Strings[53] + "\n", LogWindow.GoodColor);
            log.AddPauseTime(DateTime.Now.Ticks);

            // Skip merging if in Test Mode
            if (options.TestMode)
            {
                log.SetTotalArchives(expectedCount);
                log.SetCurrentArchive(ROMs.Count);
                log.AppendText("\n" + expectedCount + options.Strings[54] + ROMs.Count + options.Strings[55], LogWindow.GoodColor);
                log.SelectFilesOutput();
                return;
            }

            log.SetTotalArchives(ROMs.Count);

            #endregion
            #region <Prepare Process>

            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
             * / Assemble the appropriate arguments for the chosen compressor
             * / and decompressor. Prepare the process for execution.
             * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            coArgMid = "-w\"";
            if (options.OutputCompression == "7z")
            {
                coArgStart = "a -bd -t7z -ms -mmt -m0=lzma -m0fb=128 ";
            }
            else if (options.OutputCompression == "zip")
            {
                coArgStart = "a -bd -tzip -mx=9 -mfb=128 ";
            }
            else if (options.OutputCompression == "ace")
            {
                coArgStart = "a -m5 -d4096 -s -c2 -std ";
                coArgMid   = "-t\"";
            }
            else
            {
                coArgStart = "a -m5 -mdG -s ";
            }
            coArgMid += options.WorkingFolder.Substring(0, options.WorkingFolder.Length - 1) + "\" \"" + options.OutputFolder;
            coArgEnd  = "." + options.OutputCompression + "\" @\"" + options.WorkingFolder + TEMP_FILE + "\"";

            deArgStart  = decompressExe.EndsWith("7za.exe") ? "e -aos \"" : "e -o- \"";
            deArgStart += options.SourceFolder;
            deArgEnd    = decompressExe.EndsWith("7za.exe") ? "." + options.SourceCompression + "\" -o\"" : "." + options.SourceCompression + "\" \"";
            deArgEnd   += TEMP_DIR + "\"";

            if (options.SourceCompression != "none")
            {
                if (Directory.Exists(TEMP_DIR))
                {
                    try { Directory.Delete(TEMP_DIR, true); }
                    catch { doError(options.Strings[88]); return; }
                }
            }

            log.Exe.StartInfo.UseShellExecute        = false;
            log.Exe.StartInfo.CreateNoWindow         = true;
            log.Exe.StartInfo.RedirectStandardOutput = true;
            log.Exe.StartInfo.FileName = compressExe;
            if (options.SourceCompression != "none")
            {
                log.Exe.StartInfo.WorkingDirectory = TEMP_DIR;
            }
            else
            {
                log.Exe.StartInfo.WorkingDirectory = options.SourceFolder;
            }

            #endregion
            #region <Perform Merge>

            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
             * / For each game, decompress if necessary, write a list file,
             * / then compress. Output stats.
             * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
            log.ClearText();
            log.AppendText(options.Strings[0] + " " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + " - " + DateTime.Now.ToString() + "\n", LogWindow.GoodColor);
            log.AppendText(options.SetName + " " + options.Version + " - " + options.Strings[57] + options.DesiredRAM + options.Strings[58] + "\n", LogWindow.GoodColor);

            try { Directory.CreateDirectory(options.OutputFolder); }
            catch { doError(options.Strings[59] + "\n(" + options.OutputFolder + ")"); return; }

            foreach (DictionaryEntry entry in ROMs)
            {
                #region <Update Log Window>
                if (log.Canceled)
                {
                    break;
                }
                // Update log window
                log.SetPercentCompletion(actualCount * 100 / expectedCount);

                if (log.Paused)
                {
                    log.StopTimer();
                    pauseTime = DateTime.Now.Ticks;
                    while (log.Paused)
                    {
                        Thread.Sleep(50);
                    }
                    if (log.Canceled)
                    {
                        break;
                    }
                    log.AddPauseTime(DateTime.Now.Ticks - pauseTime);
                    log.StartTimer();
                }

                parent = entry.Key.ToString();
                log.SetCurrentArchive(archiveNumber++);
                log.AppendText("\n" + parent + "\n", LogWindow.NormalColor, LogWindow.BoldUnderlineFont);

                #endregion
                inputSizeBytes = 0;
                // If the output file already exists, get its stats and continue.
                fileStats = new FileInfo(options.OutputFolder + parent + "." + options.OutputCompression);
                if (fileStats.Exists)
                {
                    opStart = DateTime.Now;
                    #region <Get Stats from Existing File>
                    log.Exe.StartInfo.Arguments        = "l \"" + fileStats.FullName + "\"";
                    log.Exe.StartInfo.WorkingDirectory = options.CurrentFolder;
                    if (log.Canceled)
                    {
                        break;
                    }
                    try { log.Exe.Start(); }
                    catch { doError(options.Strings[60] + "\n(" + compressExe + ")"); return; }
                    fullOutput = log.Exe.StandardOutput.ReadToEnd();
                    try { log.Exe.WaitForExit(); log.Exe.Close(); }
                    catch { doError(options.Strings[61] + "\n(" + compressExe + ")"); return; }
                    if (log.Canceled)
                    {
                        break;
                    }

                    try {
                        splitText = fullOutput.Split(ENDLINE);
                        if (options.OutputCompression == "ace")
                        {
                            loop           = 0;
                            inputSizeBytes = 0;
                            while (!splitText[++loop].StartsWith("Contents of archive"))
                            {
                                ;
                            }
                            loop += 7;
                            while (!splitText[++loop].Replace(" ", "").Equals(""))
                            {
                                split2          = splitText[loop++].Split(PIPE);
                                inputSizeBytes += int.Parse(split2[3]);
                            }
                            loop++;
                            fileCount = int.Parse(splitText[++loop].Split(SPACE)[1].Replace(".", ""));
                        }
                        else if (options.OutputCompression == "rar")
                        {
                            loop      = 0;
                            splitText = splitText[splitText.Length - 5].Split(SPACE);
                            while (splitText[loop++] == "")
                            {
                                ;
                            }
                            fileCount = int.Parse(splitText[loop - 1]);
                            while (splitText[loop++] == "")
                            {
                                ;
                            }
                            inputSizeBytes = int.Parse(splitText[loop - 1]);
                        }
                        else
                        {
                            loop      = 0;
                            splitText = splitText[splitText.Length - 3].Split(SPACE);
                            while (splitText[loop++] == "")
                            {
                                ;
                            }
                            inputSizeBytes = int.Parse(splitText[loop - 1]);
                            while (splitText[loop++] == "")
                            {
                                ;
                            }
                            while (splitText[loop++] == "")
                            {
                                ;
                            }
                            fileCount = int.Parse(splitText[loop - 1]);
                        }
                    }
                    catch { doError(options.Strings[62] + "\n" + fullOutput); return; }
                    if (options.Arguments)
                    {
                        if (options.OutputCompression == "7z")
                        {
                            inputSize = (long)Math.Ceiling((inputSizeBytes / 1024.0) / 1024.0);
                            if (inputSize <= options.UltraDict)
                            {
                                settings = "-mx=9 -m0d=" + inputSize + "m ";
                            }
                            else if (inputSize <= options.MaxDict)
                            {
                                settings = "-mx=7 -m0d=" + inputSize + "m ";
                            }
                            else
                            {
                                settings = "-mx=7 -m0d=" + options.MaxDict + "m ";
                            }
                        }
                        log.AppendText(options.Strings[75] + coArgStart + settings + "\n", LogWindow.ExtraColor);
                    }
                    log.AppendText(opStart.ToString() + String.Format(" - {0:N0} " + options.Strings[63] + " {1:N0} ", inputSizeBytes, fileCount));
                    if (fileCount == 1)
                    {
                        log.AppendText(options.Strings[64]);
                    }
                    else
                    {
                        log.AppendText(options.Strings[65]);
                    }
                    log.AppendText(" " + options.Strings[66] + "\n");
                    if (options.SourceCompression != "none")
                    {
                        log.Exe.StartInfo.WorkingDirectory = TEMP_DIR;
                    }
                    else
                    {
                        log.Exe.StartInfo.WorkingDirectory = options.SourceFolder;
                    }
                    #endregion
                }
                else
                {
                    opStart = DateTime.Now;
                    if (options.SourceCompression != "none")
                    {
                        #region <Decompress>
                        // If we need to, decompress all relevant files.
                        try { Directory.CreateDirectory(TEMP_DIR); }
                        catch { doError(options.Strings[67] + "\n(" + TEMP_DIR + ")"); return; }

                        log.AppendText(options.Strings[68]);
                        log.Exe.StartInfo.FileName = decompressExe;
                        files = (StringCollection)(entry.Value);
                        string[] temp;
                        if (alternateParents.Contains(parent))
                        {
                            temp = new string[((StringCollection)(alternateParents[parent])).Count + 1];
                            ((StringCollection)(alternateParents[parent])).CopyTo(temp, 0);
                            temp[temp.Length - 1] = parent;
                        }
                        else
                        {
                            temp    = new string[1];
                            temp[0] = parent;
                        }
                        foreach (string str in files)
                        {
                            if (File.Exists(options.SourceFolder + str + "." + options.SourceCompression))
                            {
                                log.Exe.StartInfo.Arguments = deArgStart + str + deArgEnd;
                                if (log.Canceled)
                                {
                                    break;
                                }
                                try { log.Exe.Start(); }
                                catch { doError(options.Strings[60] + "\n(" + decompressExe + ")"); return; }
                                if (options.Background)
                                {
                                    try { log.Exe.PriorityClass = ProcessPriorityClass.Idle; } catch { }
                                }
                                log.Exe.StandardOutput.ReadToEnd();
                                try { log.Exe.WaitForExit(); log.Exe.Close(); }
                                catch { doError(options.Strings[61] + "\n(" + decompressExe + ")"); return; }
                            }
                        }
                        foreach (string str in temp)
                        {
                            if (File.Exists(options.SourceFolder + str + "." + options.SourceCompression))
                            {
                                log.Exe.StartInfo.Arguments = deArgStart + str + deArgEnd;
                                if (log.Canceled)
                                {
                                    break;
                                }
                                try { log.Exe.Start(); }
                                catch { doError(options.Strings[60] + "\n(" + decompressExe + ")"); return; }
                                if (options.Background)
                                {
                                    try { log.Exe.PriorityClass = ProcessPriorityClass.Idle; } catch { }
                                }
                                log.Exe.StandardOutput.ReadToEnd();
                                try { log.Exe.WaitForExit(); log.Exe.Close(); }
                                catch { doError(options.Strings[61] + "\n(" + decompressExe + ")"); return; }
                            }
                        }
                        if (log.Canceled)
                        {
                            break;
                        }

                        log.Exe.StartInfo.FileName = compressExe;
                        log.AppendText(options.Strings[53] + "\n");
                        #endregion
                    }
                    #region <Create List File>
                    // Create a list file containing only valid entries and gather stats.
                    try { outputWriter = new StreamWriter(options.WorkingFolder + TEMP_FILE); }
                    catch { doError(options.Strings[69]); return; }

                    files     = (StringCollection)(entry.Value);
                    fileCount = 0;
                    lastFound = "";
                    foreach (string str in files)
                    {
                        matched = false;
                        foreach (string ext in romExtensions)
                        {
                            try {
                                if (options.SourceCompression != "none")
                                {
                                    fileStats = new FileInfo(TEMP_DIR + str + "." + ext);
                                }
                                else
                                {
                                    fileStats = new FileInfo(options.SourceFolder + str + "." + ext);
                                }
                                if (fileStats.Exists)
                                {
                                    if (matched)
                                    {
                                        doError(options.Strings[70] + "\n" + lastFound + "\n" + fileStats.Name); return;
                                    }
                                    lastFound = fileStats.Name;
                                    matched   = true;
                                    fileCount++;
                                    inputSizeBytes += fileStats.Length;
                                    try { outputWriter.WriteLine(str + "." + ext); }
                                    catch {
                                        doError(options.Strings[71]);
                                        try { outputWriter.Flush(); outputWriter.Close(); }
                                        catch { }
                                        return;
                                    }
                                }
                            }
                            catch { doError(options.Strings[72] + "\n(" + str + ")"); return; }
                        }
                        if (!matched)
                        {
                            doError(options.Strings[73] + " \"" + str + ".*\""); return;
                        }
                    }
                    try { outputWriter.Flush(); outputWriter.Close(); }
                    catch { doError(options.Strings[74]); return; }
                    #endregion
                    #region <Execute Compressor>
                    // If working with 7-zip, find the optimum arguments.
                    if (options.OutputCompression == "7z")
                    {
                        inputSize = (long)Math.Ceiling((inputSizeBytes / 1024.0) / 1024.0);
                        if (inputSize <= options.UltraDict)
                        {
                            settings = "-mx=9 -m0d=" + inputSize + "m ";
                        }
                        else if (inputSize <= options.MaxDict)
                        {
                            settings = "-mx=7 -m0d=" + inputSize + "m ";
                        }
                        else
                        {
                            settings = "-mx=7 -m0d=" + options.MaxDict + "m ";
                        }
                    }

                    if (options.Arguments)
                    {
                        log.AppendText(options.Strings[75] + coArgStart + settings + "\n", LogWindow.ExtraColor);
                    }

                    log.AppendText(opStart.ToString() + " - " + String.Format("{0:N0} " + options.Strings[63] + " {1:N0} ", inputSizeBytes, fileCount));
                    if (fileCount == 1)
                    {
                        log.AppendText(options.Strings[64]);
                    }
                    else
                    {
                        log.AppendText(options.Strings[65]);
                    }
                    log.AppendText(" " + options.Strings[76] + "\n");

                    // Execute the compressor and filter its output.
                    if (log.Canceled)
                    {
                        break;
                    }
                    log.Exe.StartInfo.Arguments = coArgStart + settings + coArgMid + parent + coArgEnd;
                    log.CurrentOutputFileName   = options.OutputFolder + parent + "." + options.OutputCompression;
                    try { log.Exe.Start(); }
                    catch { doError(options.Strings[60] + "\n(" + compressExe + ")"); return; }
                    if (options.Background)
                    {
                        try { log.Exe.PriorityClass = ProcessPriorityClass.Idle; } catch { }
                    }
                    fullOutput = log.Exe.StandardOutput.ReadToEnd();
                    try { log.Exe.WaitForExit(); log.Exe.Close(); }
                    catch { doError(options.Strings[61] + "\n(" + compressExe + ")"); return; }
                    log.CurrentOutputFileName = "~gmt~";
                    if (log.Canceled)
                    {
                        break;
                    }

                    fileStats = new FileInfo(options.OutputFolder + parent + "." + options.OutputCompression);
                    if (!fileStats.Exists)
                    {
                        doError(options.Strings[77] + compressExe + " " + log.Exe.StartInfo.Arguments + ")\n");
                        log.AppendText(fullOutput, LogWindow.BadColor);
                        return;
                    }

                    if (!options.SourceCompression.Equals("none"))
                    {
                        // Clean out the temporary folder
                        FileInfo[] tempFiles = (new DirectoryInfo(TEMP_DIR)).GetFiles();
                        foreach (FileInfo fi in tempFiles)
                        {
                            try { fi.Attributes = FileAttributes.Normal; }
                            catch { doError(options.Strings[72]); return; }
                        }
                        try { Directory.Delete(TEMP_DIR, true); }
                        catch { doError(options.Strings[56]); return; }
                    }
                    #endregion
                }
                #region <Add Stats>
                actualCount     += fileCount;
                totalInputSize  += inputSizeBytes;
                totalOutputSize += fileStats.Length;

                string   time = options.Strings[40];
                TimeSpan t    = TimeSpan.FromTicks(DateTime.Now.Ticks - opStart.Ticks);
                time += (t.Days * 24 + t.Hours) + ":";
                if (t.Minutes < 10)
                {
                    time += "0";
                }
                time += t.Minutes + ":";
                if (t.Seconds < 10)
                {
                    time += "0";
                }
                time += t.Seconds;

                log.AppendText(DateTime.Now.ToString() + String.Format(" - {0:N0} " + options.Strings[87] + " (" + fileStats.Length * 100 / inputSizeBytes + options.Strings[78] + "). " + time + ".\n", fileStats.Length));
                #endregion
                #region <Delete Files>
                if (options.SourceCompression.Equals("none") && options.DeleteFiles)
                {
                    log.AppendText(options.Strings[79], LogWindow.BadColor);
                    n     = "";
                    files = (StringCollection)(entry.Value);
                    foreach (string str in files)
                    {
                        foreach (string ext in romExtensions)
                        {
                            fileStats = new FileInfo(options.SourceFolder + str + "." + ext);
                            if (fileStats.Exists)
                            {
                                try {
                                    fileStats.Attributes = FileAttributes.Normal;
                                    fileStats.Delete();
                                }
                                catch {
                                    log.AppendText("\n" + options.Strings[80] + " \"" + fileStats.FullName + "\"", LogWindow.BadColor);
                                    n = "\n";
                                }
                            }
                        }
                    }
                    log.AppendText(n + options.Strings[53] + "\n", LogWindow.BadColor);
                }
                #endregion
                #region <Update Log Window>
                log.SetProjectedSize(totalOutputSize * expectedCount / actualCount);

                log.SetPercentCompression((int)(totalOutputSize * 100 / totalInputSize));
                log.SetTimeRemaining((log.GetElapsedTicks() / actualCount) * (expectedCount - actualCount));
                #endregion
            }
            #endregion
            #region <Clean Up>
            try { File.Delete(options.WorkingFolder + TEMP_FILE); }
            catch { doError(options.Strings[81]); }

            if (log.Canceled)
            {
                doError(options.Strings[82] + actualCount * 100 / expectedCount + "%.");
                if (options.SourceCompression != "none")
                {
                    // Clean out the temporary folder
                    try {
                        FileInfo[] tempFiles = (new DirectoryInfo(TEMP_DIR)).GetFiles();
                        foreach (FileInfo fi in tempFiles)
                        {
                            fi.Attributes = FileAttributes.Normal;
                        }
                        Directory.Delete(TEMP_DIR, true);
                    }
                    catch { }
                }
            }
            else
            {
                log.AppendText("\n" + options.Strings[83], LogWindow.GoodColor, LogWindow.BoldUnderlineFont);
                log.AppendText(String.Format("\n{0:N0} " + options.Strings[63] + " {1:N0} " + options.Strings[84], totalInputSize, actualCount), LogWindow.GoodColor);
                log.AppendText(String.Format("\n{0:N0} " + options.Strings[87] + " (" + totalOutputSize * 100 / totalInputSize + options.Strings[78] + ") " + options.Strings[85] + " {1:N0} " + options.Strings[65] + " (" + ROMs.Count * 100 / actualCount + options.Strings[78] + ").\n", totalOutputSize, ROMs.Count), LogWindow.GoodColor);
                string   time = options.Strings[40];
                TimeSpan t    = TimeSpan.FromTicks(log.GetElapsedTicks());
                time += (t.Days * 24 + t.Hours) + ":";
                if (t.Minutes < 10)
                {
                    time += "0";
                }
                time += t.Minutes + ":";
                if (t.Seconds < 10)
                {
                    time += "0";
                }
                time += t.Seconds;
                log.AppendText(time + "\n", LogWindow.GoodColor);
                log.AppendText(options.Strings[28] + " - " + DateTime.Now.ToString() + "\n", LogWindow.GoodColor);
            }
            #endregion
        }
Esempio n. 36
0
        /// <summary>
        /// Reads a string array from the stream.
        /// </summary>
        public StringCollection ReadStringArray(string fieldName)
        {
            bool isNil = false;

            StringCollection values = new StringCollection();
                                    
            if (BeginField(fieldName, true, out isNil))
            {                                
                PushNamespace(Namespaces.OpcUaXsd);
                
                while (MoveToElement("String"))
                {
                    values.Add(ReadString("String"));
                }

                // check the length.
                if (m_context.MaxArrayLength > 0 && m_context.MaxArrayLength < values.Count)
                {
                    throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
                }

                PopNamespace();

                EndField(fieldName);
                return values;
            }

            if (isNil)
            {
                return null;
            }

            return values;
        }
Esempio n. 37
0
        }         // FormatSafeInvariant

        // ----------------------------------------------------------------------
        /// <summary>
        /// Splits a string in the same way as the System.String.Split() method but
        /// with support for special treatment for escaped characters and for quoted
        /// sections which won't be split.
        /// </summary>
        /// <remarks>
        /// Escaping supports the following special treatment:
        /// <list type="bullet">
        /// <item>escape is followed by 'n': a new line character is inserted</item>
        /// <item>escape is followed by 'r': a form feed character is inserted</item>
        /// <item>escape is followed by 't': a tabulator character is inserted</item>
        /// <item>escape is followed by 'x': the next two characters are interpreted
        /// as a hex code of the character to be inserted</item>
        /// <item>any other character after the escape is inserted literally</item>
        /// </list>
        /// Escaping is applied within and outside of quoted sections.
        /// </remarks>
        /// <param name="toSplit">the string to split</param>
        /// <param name="quote">the quoting character, e.g. '&quot;'</param>
        /// <param name="escape">an escaping character to use both within and outside
        /// of quoted sections, e.g. '\\'</param>
        /// <param name="includeEmptyUnquotedSections">whether to return zero-length sections
        /// outside of quotations or not. empty sections adjacent to a quoted section are
        /// never returned.</param>
        /// <param name="separator">the separator character(s) which will be used to
        /// split the string outside of quoted sections</param>
        /// <returns>the array of sections into which the string has been split up.
        /// never null but possibly empty.</returns>
        public static string[] SplitQuoted(string toSplit, char quote, char escape,
                                           bool includeEmptyUnquotedSections, params char[] separator)
        {
            if (toSplit == null)
            {
                throw new ArgumentNullException("toSplit");
            }
            if (separator == null || separator.Length == 0)
            {
                throw new ArgumentNullException("separator");
            }
            string separators = new string( separator );

            if (separators.IndexOf(quote) >= 0 || separators.IndexOf(escape) >= 0)
            {
                throw new ArgumentException(Strings.StringToolSeparatorIncludesQuoteOrEscapeChar, "separator");
            }

            StringCollection sections = new StringCollection();

            StringBuilder section         = null;
            int           length          = toSplit.Length;
            bool          inQuotedSection = false;

            for (int i = 0; i < length; i++)
            {
                char c = toSplit[i];
                if (c == escape)
                {
                    if (i < length - 1)
                    {
                        if (section == null)
                        {
                            section = new StringBuilder();
                        }
                        i++;
                        c = toSplit[i];
                        switch (c)
                        {
                        case 'n':
                            section.Append('\n');
                            break;

                        case 'r':
                            section.Append('\r');
                            break;

                        case 't':
                            section.Append('\t');
                            break;

                        case 'x':
                            if (i < length - 2)
                            {
                                int  upperHexNibble = GetHexValue(toSplit[i + 1]) * 16;
                                int  lowerHexNibble = GetHexValue(toSplit[i + 2]);
                                char hexChar        = (char)(upperHexNibble + lowerHexNibble);
                                section.Append(hexChar);
                                i += 2;
                            }
                            else
                            {
                                throw new ArgumentException(Strings.StringToolMissingEscapedHexCode, "toSplit");
                            }
                            break;

                        default:
                            section.Append(c);
                            break;
                        }
                    }
                    else
                    {
                        throw new ArgumentException(Strings.StringToolMissingEscapedChar, "toSplit");
                    }
                }
                else if (c == quote)
                {
                    if (section != null)
                    {
                        sections.Add(section.ToString());
                        section = null;
                    }
                    else if (inQuotedSection)
                    {
                        sections.Add(string.Empty);
                    }
                    inQuotedSection = !inQuotedSection;
                }
                else if (separators.IndexOf(c) >= 0)
                {
                    if (inQuotedSection)
                    {
                        if (section == null)
                        {
                            section = new StringBuilder();
                        }
                        section.Append(c);
                    }
                    else
                    {
                        if (section != null)
                        {
                            sections.Add(section.ToString());
                            section = null;
                        }
                        else if (includeEmptyUnquotedSections)
                        {
                            if (i == 0 || separators.IndexOf(toSplit[i - 1]) >= 0)
                            {
                                sections.Add(string.Empty);
                            }
                        }
                    }
                }
                else
                {
                    if (section == null)
                    {
                        section = new StringBuilder();
                    }
                    section.Append(c);
                }
            }
            if (inQuotedSection)
            {
                throw new ArgumentException(Strings.StringToolUnbalancedQuotes, "toSplit");
            }
            if (section != null)
            {
                sections.Add(section.ToString());
            }

            string[] sectionArray = new string[sections.Count];
            sections.CopyTo(sectionArray, 0);
            return(sectionArray);
        }         // SplitQuoted
Esempio n. 38
0
 public static void CountTest(StringCollection collection, string[] data)
 {
     Assert.Equal(data.Length, collection.Count);
     collection.Clear();
     Assert.Equal(0, collection.Count);
     collection.Add("one");
     Assert.Equal(1, collection.Count);
     collection.AddRange(data);
     Assert.Equal(1 + data.Length, collection.Count);
 }
Esempio n. 39
0
        //<ships PXKeywords="SUBJECT_AREA">MenuSelection.PresText</ships>



        /// <PXKeyword name="DATABASE">
        ///   <rule>
        ///     <description>The value, which is language dependent, is read from the database config file
        ///     descriptions.description element</description>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="MATRIX">
        ///   <rule>
        ///     <description>The value is set to the Precode of the first selected content</description>
        ///     <table modelName ="Contents">
        ///     <column modelName="PresCode"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="MAINTABLE">
        ///   <rule>
        ///     <description></description>
        ///     <table modelName ="MainTable">
        ///     <column modelName="MainTable"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="TABLEID">
        ///   <rule>
        ///     <description>It's only set if the database column contains av value</description>
        ///     <table modelName ="MainTable">
        ///     <column modelName="TableId"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="SUBJECT_CODE">
        ///   <rule>
        ///     <description></description>
        ///     <table modelName ="MainTable">
        ///     <column modelName="SubjectCode"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="SUBJECT_AREA">
        ///   <rule>
        ///     <description></description>
        ///     <table modelName ="MenuSelection">
        ///     <column modelName="Prestext"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="INFOFILE">
        ///   <rule>
        ///     <description></description>
        ///     <table modelName ="MainTable">
        ///     <column modelName="ProductCode"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="CONTENTS">
        ///   <rule>
        ///     <description>If only one content i selected the value from Contents.PresText is used, otherwise the
        ///     MainTable.PresTexS is used </description>
        ///     <table modelName ="MainTable">
        ///     <column modelName="PresTextS"/>
        ///     </table>
        ///     <table modelName ="Contents">
        ///     <column modelName="PresText"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="UNITS">
        ///   <rule>
        ///     <description>Even if UNITS is specified for each contents Paxiom or more correct PX-Axis expect a UNIT keyword for the whole file.
        ///     we take UNIT for the first keyword.</description>
        ///     <table modelName ="CONTENTS">
        ///     <column modelName="UNIT"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="STUB">
        ///   <rule>
        ///     <description>If variable type is classificaion or time then MainTableVariable.Variable is used.
        ///     If variable is a contentsvariable then the value of PXSqlMeta.mContVariableCode = "ContentsCode" is used.</description>
        ///     <table modelName ="MainTableVariable">
        ///     <column modelName="Variable"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="HEADING">
        ///   <rule>
        ///     <description>If variable type is classificaion or time then MainTableVariable.Variable is used.
        ///     If variable is a contentsvariable then the value of PXSqlMeta.mContVariableCode = "ContentsCode" is used.</description>
        ///     <table modelName ="MainTableVariable">
        ///     <column modelName="Variable"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="DECIMALS">
        ///   <rule>
        ///     <description>If more contents are selected with different StoreDecimals, then DECIMALS is set to the highest one</description>
        ///     <table modelName ="Contents">
        ///     <column modelName="StoreDecimals"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        /// <PXKeyword name="SHOWDECIMALS">
        ///   <rule>
        ///     <description>If more contents are selected with different PresDecimals, then SHOWDECIMALS is set to the lowest one</description>
        ///     <table modelName ="Contents">
        ///     <column modelName="PresDecimals"/>
        ///     </table>
        ///   </rule>
        /// </PXKeyword>
        public void ParseMeta(PCAxis.Paxiom.IPXModelParser.MetaHandler handler, StringCollection LanguageCodes)
        {
            string           noLanguage = null;
            string           subkey     = null;
            StringCollection values     = new StringCollection();

            // MATRIX
            values.Clear();
            values.Add(meta.Contents[meta.FirstContents].PresCode);
            handler(PXKeywords.MATRIX, noLanguage, subkey, values);


            // MAINTABLE

            values.Clear();
            values.Add(this.MainTable);
            handler(PXKeywords.MAINTABLE, noLanguage, subkey, values);


            // TABLEID

            if (!string.IsNullOrEmpty(this.TableId.Trim(' ')))
            {
                values.Clear();
                values.Add(this.TableId);
                handler(PXKeywords.TABLEID, noLanguage, subkey, values);
            }

            // SUBJECT-CODE

            values.Clear();
            values.Add(this.mSubjectCode);
            handler(PXKeywords.SUBJECT_CODE, noLanguage, subkey, values);

            //SUBJECT-AREA

            foreach (string langCode in mSubjectAreaByLanguage.Keys)
            {
                values.Clear();
                values.Add(mSubjectAreaByLanguage[langCode]);
                handler(PXKeywords.SUBJECT_AREA, langCode, subkey, values);
            }

            // DATABASE
            foreach (string langCode in LanguageCodes)
            {
                values.Clear();
                // values.Add(this.mDataStorageRow.DatabaseName);
                //values.Add(meta.Config.Database.id);  // Was a bug. Before database came from DataStorage.DatabaseName
                values.Add(meta.Config.GetDescription(langCode));// Corrected to description
                handler(PXKeywords.DATABASE, langCode, subkey, values);
            }

            //DESCRIPTION
            // Removed should not be sent to PAXIOM 07.04.2011
            // se Reqtest 319.


            // FIRST_PUBLISHED

            values.Clear();
            values.Add(this.mtRow.FirstPublished);
            handler(PXKeywords.FIRST_PUBLISHED, null, subkey, values);


            // INFOFILE

            values.Clear();
            values.Add(this.ProductCode);
            handler(PXKeywords.INFOFILE, noLanguage, subkey, values);

            // META_ID
            if (!String.IsNullOrEmpty(this.mtRow.MetaId))
            {
                values.Clear();
                values.Add(this.mtRow.MetaId);
                handler(PXKeywords.META_ID, noLanguage, subkey, values);
            }
            //PX_SERVER
            // Removed should not be sent to PAXIOM 07.04.2011
            // se Reqtest 324.


            // CONTENTS
            foreach (string langCode in LanguageCodes)
            {
                values.Clear();
                if (this.meta.PXMetaAdmValues.AllwaysUseMaintablePrestextSInDynamicTitle)
                {
                    values.Add(meta.MainTable.getPresTextS(langCode));
                }
                else if (meta.Contents.Count > 1)
                {
                    // Contents should be set to maintable.PresTexts
                    values.Add(meta.MainTable.getPresTextS(langCode));
                }
                else
                {
                    //values.Add(meta.Contents[meta.FirstContents].PresTextS[langCode]);
                    // bugs reported from sweden, PresTextS is not mandatory, PresText should be used.
                    values.Add(meta.Contents[meta.FirstContents].PresText[langCode]);
                }
                handler(PXKeywords.CONTENTS, langCode, subkey, values);
            }

            //UNITS
            // even if UNITS is specified for each contents Paxiom or more correct PX-Axis expect a UNIT keyword for the hole file.
            // we take UNIT for the first keyword.
            foreach (string langCode in LanguageCodes)
            {
                values.Clear();
                values.Add(meta.Contents[meta.FirstContents].UNIT[langCode]);
                handler(PXKeywords.UNITS, langCode, null, values);
            }

            //STUB
            values.Clear();
            foreach (PXSqlVariable var in meta.Stubs)
            {
                values.Add(var.Name);
            }
            handler(PXKeywords.STUB, noLanguage, subkey, values);
            //HEADING
            values.Clear();
            foreach (PXSqlVariable var in meta.Headings)
            {
                values.Add(var.Name);
            }
            handler(PXKeywords.HEADING, noLanguage, subkey, values);

            // Decimals stuff

            values.Clear();
            values.Add(meta.DecimalHandler.StoreDecimals.ToString());
            handler(PXKeywords.DECIMALS, noLanguage, subkey, values);

            values.Clear();
            values.Add(meta.DecimalHandler.ShowDecimals.ToString());
            handler(PXKeywords.SHOWDECIMALS, noLanguage, subkey, values);
            values = null;
        }
        static Draw2DTextRect()
        {
            propertyNames = new StringCollection();
            propertyNames.Add("Rectangle");
            propertyNames.Add("CornerRadius");
            propertyNames.Add("Fill");
            propertyNames.Add("FillColor");
            propertyNames.Add("LineWidth");
            propertyNames.Add("RotateAngle");
            propertyNames.Add("TextString");
            propertyNames.Add("TextFont");
            propertyNames.Add("TextColor");
            propertyNames.Add("WordWrap");
            propertyNames.Add("HideRectangle");
            propertyNames.Add("TextAlign");

            propertyNames.Add("EnableEditing");
            propertyNames.Add("TextBoxWidth");
            propertyNames.Add("TabIndex");
        }
Esempio n. 41
0
        /// <summary>
        /// Parses the specified path and returns the portion determined by the
        /// boolean parameters.
        /// </summary>
        protected override void ProcessRecord()
        {
            StringCollection pathsToParse = new StringCollection();

            if (Resolve)
            {
                CmdletProviderContext currentContext = CmdletProviderContext;

                foreach (string path in Path)
                {
                    // resolve the paths and then parse each one.

                    Collection <PathInfo> resolvedPaths;

                    try
                    {
                        resolvedPaths =
                            SessionState.Path.GetResolvedPSPathFromPSPath(path, currentContext);
                    }
                    catch (PSNotSupportedException notSupported)
                    {
                        WriteError(
                            new ErrorRecord(
                                notSupported.ErrorRecord,
                                notSupported));
                        continue;
                    }
                    catch (DriveNotFoundException driveNotFound)
                    {
                        WriteError(
                            new ErrorRecord(
                                driveNotFound.ErrorRecord,
                                driveNotFound));
                        continue;
                    }
                    catch (ProviderNotFoundException providerNotFound)
                    {
                        WriteError(
                            new ErrorRecord(
                                providerNotFound.ErrorRecord,
                                providerNotFound));
                        continue;
                    }
                    catch (ItemNotFoundException pathNotFound)
                    {
                        WriteError(
                            new ErrorRecord(
                                pathNotFound.ErrorRecord,
                                pathNotFound));
                        continue;
                    }

                    foreach (PathInfo resolvedPath in resolvedPaths)
                    {
                        try
                        {
                            if (InvokeProvider.Item.Exists(resolvedPath.Path, currentContext))
                            {
                                pathsToParse.Add(resolvedPath.Path);
                            }
                        }
                        catch (PSNotSupportedException notSupported)
                        {
                            WriteError(
                                new ErrorRecord(
                                    notSupported.ErrorRecord,
                                    notSupported));
                            continue;
                        }
                        catch (DriveNotFoundException driveNotFound)
                        {
                            WriteError(
                                new ErrorRecord(
                                    driveNotFound.ErrorRecord,
                                    driveNotFound));
                            continue;
                        }
                        catch (ProviderNotFoundException providerNotFound)
                        {
                            WriteError(
                                new ErrorRecord(
                                    providerNotFound.ErrorRecord,
                                    providerNotFound));
                            continue;
                        }
                        catch (ItemNotFoundException pathNotFound)
                        {
                            WriteError(
                                new ErrorRecord(
                                    pathNotFound.ErrorRecord,
                                    pathNotFound));
                            continue;
                        }
                    }
                }
            }
            else
            {
                pathsToParse.AddRange(Path);
            }

            // Now parse each path

            for (int index = 0; index < pathsToParse.Count; ++index)
            {
                string result = null;

                switch (ParameterSetName)
                {
                case isAbsoluteSet:
                    string ignored;
                    bool   isPathAbsolute =
                        SessionState.Path.IsPSAbsolute(pathsToParse[index], out ignored);

                    WriteObject(isPathAbsolute);
                    continue;

                case qualifierSet:
                    int separatorIndex = pathsToParse[index].IndexOf(":", StringComparison.CurrentCulture);

                    if (separatorIndex < 0)
                    {
                        FormatException e =
                            new FormatException(
                                StringUtil.Format(NavigationResources.ParsePathFormatError, pathsToParse[index]));
                        WriteError(
                            new ErrorRecord(
                                e,
                                "ParsePathFormatError",     // RENAME
                                ErrorCategory.InvalidArgument,
                                pathsToParse[index]));
                        continue;
                    }
                    else
                    {
                        // Check to see if it is provider or drive qualified

                        if (SessionState.Path.IsProviderQualified(pathsToParse[index]))
                        {
                            // The plus 2 is for the length of the provider separator
                            // which is "::"

                            result =
                                pathsToParse[index].Substring(
                                    0,
                                    separatorIndex + 2);
                        }
                        else
                        {
                            result =
                                pathsToParse[index].Substring(
                                    0,
                                    separatorIndex + 1);
                        }
                    }
                    break;

                case parentSet:
                case literalPathSet:
                    try
                    {
                        result =
                            SessionState.Path.ParseParent(
                                pathsToParse[index],
                                String.Empty,
                                CmdletProviderContext,
                                true);
                    }
                    catch (PSNotSupportedException)
                    {
                        // Since getting the parent path is not supported,
                        // the provider must be a container, item, or drive
                        // provider.  Since the paths for these types of
                        // providers can't be split, asking for the parent
                        // is asking for an empty string.
                        result = String.Empty;
                    }

                    break;

                case leafSet:
                case leafBaseSet:
                case extensionSet:
                    try
                    {
                        // default handles leafSet
                        result =
                            SessionState.Path.ParseChildName(
                                pathsToParse[index],
                                CmdletProviderContext,
                                true);
                        if (LeafBase)
                        {
                            result = System.IO.Path.GetFileNameWithoutExtension(result);
                        }
                        else if (Extension)
                        {
                            result = System.IO.Path.GetExtension(result);
                        }
                    }
                    catch (PSNotSupportedException)
                    {
                        // Since getting the leaf part of a path is not supported,
                        // the provider must be a container, item, or drive
                        // provider.  Since the paths for these types of
                        // providers can't be split, asking for the leaf
                        // is asking for the specified path back.
                        result = pathsToParse[index];
                    }
                    catch (DriveNotFoundException driveNotFound)
                    {
                        WriteError(
                            new ErrorRecord(
                                driveNotFound.ErrorRecord,
                                driveNotFound));
                        continue;
                    }
                    catch (ProviderNotFoundException providerNotFound)
                    {
                        WriteError(
                            new ErrorRecord(
                                providerNotFound.ErrorRecord,
                                providerNotFound));
                        continue;
                    }

                    break;

                case noQualifierSet:
                    result = RemoveQualifier(pathsToParse[index]);
                    break;

                default:
                    Dbg.Diagnostics.Assert(
                        false,
                        "Only a known parameter set should be called");
                    break;
                } // switch

                if (result != null)
                {
                    WriteObject(result);
                }
            } // for each path
        }     // ProcessRecord
Esempio n. 42
0
        void Refresh_PatternsList(bool applyAllAsSelected)
        {
            if (_patternProject == null)
            {
                return;
            }

            // info
            lblPatternLanguage.Text  = _patternProject.Language;
            lblPatternDatabases.Text = _patternProject.SupportedDatabases;
            tipHints.SetToolTip(pnlPatternInfo, _patternProject.Description);
            tipHints.SetToolTip(lblPatternLanguage, _patternProject.Description);
            tipHints.SetToolTip(lblPatternDatabases, _patternProject.Description);

            // SelectedPatterns
            StringCollection selPatterns = _projectDefinaton.CodeGenSettings.SelectedPatterns;

            // Items cehcked
            _suppressItemChecked = true;
            try
            {
                // Clean up
                lstPatterns.Groups.Clear();
                lstPatterns.Items.Clear();
                var actionCopyGroupName = "Copy Action";

                // Load patterns
                List <PatternFile> patternsList = LoadPatternsInfo(_patternProject.PatternFiles);
                var patternCopyActionList       =
                    _patternProject.PatternFiles.Where(x => x.Action == PatternsListItemAction.Copy).ToList();

                // Groups
                List <string> listGroups = new List <string>();
                foreach (var item in patternsList)
                {
                    if (!listGroups.Contains(item.Options.Group))
                    {
                        ListViewGroup group = new ListViewGroup(item.Options.Group, item.Options.Group);
                        lstPatterns.Groups.Add(group);
                        listGroups.Add(item.Options.Group);
                    }
                }
                if (patternCopyActionList.Count > 0)
                {
                    if (!listGroups.Contains(actionCopyGroupName))
                    {
                        var group = new ListViewGroup(actionCopyGroupName, actionCopyGroupName);
                        lstPatterns.Groups.Add(group);
                        listGroups.Add(actionCopyGroupName);
                    }
                }

                // clear all if others should be selected
                if (applyAllAsSelected)
                {
                    selPatterns.Clear();
                }

                // Items
                foreach (var item in patternsList)
                {
                    var listItem = new ListViewItem();
                    if (applyAllAsSelected)
                    {
                        listItem.Checked = true;
                        selPatterns.Add(item.Name);
                    }
                    else
                    {
                        if (selPatterns.Contains(item.Name))
                        {
                            listItem.Checked = true;
                        }
                        else
                        {
                            listItem.Checked = false;
                        }
                    }
                    listItem.Text        = item.Name;
                    listItem.ToolTipText = item.Description + "\n" + item.ToSummaryString();
                    listItem.Group       = lstPatterns.Groups[item.Options.Group];
                    lstPatterns.Items.Add(listItem);
                }

                foreach (var file in patternCopyActionList)
                {
                    var listItem = new ListViewItem();
                    var fileName = Path.GetFileName(file.Path);

                    // BUG: doesn't support other database provider replacements
                    // BUG: will work but will display something like ":].dll" in the list
                    if (file.Path.Contains(ReplaceConsts.ProviderAssemblyReference))
                    {
                        fileName = file.Path.Replace(ReplaceConsts.ProviderAssemblyReference, "(DatabaseAssembly)");
                        fileName = Path.GetFileName(fileName);
                    }

                    if (applyAllAsSelected)
                    {
                        listItem.Checked = true;
                        selPatterns.Add(fileName);
                    }
                    else
                    {
                        if (selPatterns.Contains(fileName))
                        {
                            listItem.Checked = true;
                        }
                        else
                        {
                            listItem.Checked = false;
                        }
                    }
                    listItem.Text        = fileName;
                    listItem.ToolTipText = "Copy to: " + file.ActionCopyPath;

                    listItem.Group = lstPatterns.Groups[actionCopyGroupName];
                    lstPatterns.Items.Add(listItem);
                }
            }
            finally
            {
                _suppressItemChecked = false;
            }
        }
Esempio n. 43
0
        private static FestManagerSettings LoadAppConfigSettings()
        {
            var settings = new FestManagerSettings()
            {
                ConnectionString = Properties.Settings.Default.connectionString,
            };

            // Overwrite default settings:
            var appSettings = new StringCollection();

            foreach (SettingsProperty currentProperty in Properties.Settings.Default.Properties)
            {
                appSettings.Add(currentProperty.Name);
            }

            if (appSettings.Contains("organisation"))
            {
                settings.Organisation = (string)Properties.Settings.Default["organisation"];
            }
            if (appSettings.Contains("printDirektverkaufTwice"))
            {
                settings.PrintDirektverkaufTwice = (bool)Properties.Settings.Default["printDirektverkaufTwice"];
            }
            if (appSettings.Contains("printTwice"))
            {
                settings.PrintTwice = (bool)Properties.Settings.Default["printTwice"];
            }
            if (appSettings.Contains("printStornoOrders"))
            {
                settings.PrintStornoOrders = (bool)Properties.Settings.Default["printStornoOrders"];
            }
            if (appSettings.Contains("direktverkaufPersonalId"))
            {
                settings.DirektverkaufPersonalId = (int)Properties.Settings.Default["direktverkaufPersonalId"];
            }
            if (appSettings.Contains("direktverkaufAusgabestelleId"))
            {
                settings.DirektverkaufAusgabestelleId = (int)Properties.Settings.Default["direktverkaufAusgabestelleId"];
            }
            if (appSettings.Contains("stornoSymbol"))
            {
                settings.StornoSymbol = (string)Properties.Settings.Default["stornoSymbol"];
            }
            if (appSettings.Contains("groupElementsBeforePrint"))
            {
                settings.GroupElementsBeforePrint = (bool)Properties.Settings.Default["groupElementsBeforePrint"];
            }
            if (appSettings.Contains("einpackenSymbol"))
            {
                settings.EinpackenSymbol = (string)Properties.Settings.Default["einpackenSymbol"];
            }
            if (appSettings.Contains("tableNumbers"))
            {
                settings.TableNumbers = (bool)Properties.Settings.Default["tableNumbers"];
            }
            if (appSettings.Contains("tableNumbersRequired"))
            {
                settings.TableNumbersRequired = (bool)Properties.Settings.Default["tableNumbersRequired"];
            }

            return(settings);
        }
Esempio n. 44
0
        private void TreeView_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // ---------------------------------------------------------------
            // If the user right clicks on a node and that node isn't already
            // selected, then go select it.
            // ---------------------------------------------------------------


            //Initialise variables

            TreeNode ClickedNode = GetNodeAt(e.Location);

            //get the node in the datatree that was clicked on.
            //if the button was pressed on a non node area of the datatree
            if ((ClickedNode == null))
            {
                return;
                //do nothing.
            }

            //allow for an image 20 pixels to the left of the text of a node
            if ((e.X < ClickedNode.Bounds.Left - 20))
            {
                return;
            }

            //Don't let the user click any other nodes while this code executes

            EnableNodeSelection = false;

            bool RightClick = (e.Button == System.Windows.Forms.MouseButtons.Right);
            //is it a right mouse button click
            bool Control = (ModifierKeys == Keys.Control);
            //is control button on keyboard pressed
            bool Shift = (ModifierKeys == Keys.Shift);
            //is shift button on keyboard pressed

            StringCollection SelectedPaths = Controller.SelectedPaths;

            //get the selected paths from the controller. (stores more then one nodes path because the user can hold down the control key and select more then one node)



            //Click with a Control button OR Right Click         'TODO: this may execute for CTRL + Centre Mouse Click too, you may want to specifically exclude this later.


            if (Control)
            {
                //check to see if the clicked node has been clicked on already
                //this IndexOf is for a string "collection" NOT a string. So it it checks every string "in the collection" for an exact match with the search string. If it finds one it returns that strings index in the collection
                if (SelectedPaths.IndexOf(GetPathFromNode(ClickedNode)) == -1)
                {
                    SelectedPaths.Add(GetPathFromNode(ClickedNode));
                    //if not then add it's path to the list of selected paths
                    PreviousNode = ClickedNode;
                    //store clicked node as the previously clicked on node (used for Shift button)
                }



                //Click with a Shift button
            }
            else if (Shift)
            {
                //if (user has previously clicked on a node with the shift key down) AND (clicked node has the same parent as the previous node [they are siblings])

                if ((PreviousNode != null) && PreviousNode.Parent.Equals(ClickedNode.Parent))
                {
                    int FirstIndex = PreviousNode.Index;
                    //set to the index of the previously clicked on node
                    int LastIndex = ClickedNode.Index;
                    //set to the index of the clicked node
                    //if they clicked lower sibling before higher sibling, then rearrange the order they were clicked.
                    if (FirstIndex > LastIndex)
                    {
                        int TempIndex = LastIndex;
                        LastIndex  = FirstIndex;
                        FirstIndex = TempIndex;
                    }

                    SelectedPaths.Clear();
                    //get rid of old selected paths
                    //add the paths for all the node's between the first index and the last index, to the list of selected paths
                    for (int i = FirstIndex; i <= LastIndex; i++)
                    {
                        SelectedPaths.Add(GetPathFromNode(PreviousNode.Parent.Nodes[i]));
                    }

                    PreviousNode = ClickedNode;
                    //store clicked node as the previously clicked on node (incase Shift button is used on the next click as well)
                }


                //(Do right and left click test after the multiple select tests of Control and Shift, so that Control and Shift can work for both Left or Right mouse clicks)

                //Right Click Only
            }
            else if (RightClick)
            {
                SelectedPaths.Clear();
                //get rid of existing selected paths
                SelectedPaths.Add(GetPathFromNode(ClickedNode));
                //add new path to selected paths
                PreviousNode = ClickedNode;
                //store clicked node as the previously clicked on node (used for Shift button)


                //Left Click Only

                //if user clicked on a node and not a blank area
            }
            else if ((ClickedNode != null))
            {
                //if the user clicked again on the same thing that was already selected -> then do a Rename.

                //click on same thing that was already selected.

                if (!Controller.ApsimData.IsReadOnly && SelectedPaths.Count == 1 && SelectedPaths[0] == GetPathFromNode(ClickedNode) && ClickedNode.Level > 0)
                {
                    //if not readonly,
                    //and user has clicked once before,
                    //and what they clicked this time is the same as what they clicked last time,
                    //and they have clicked on a node that is lower down then the root node [can't rename the root node]

                    LabelEdit = true;
                    //set the tree's label edit property  to true, allowing all the nodes on the tree to have their labels edited. (needs to be set to true for Node.BeginEdit() to work)
                    FirstTimeRename = true;
                    ClickedNode.BeginEdit();
                    //call the inbuilt tree node function that allows the user to edit the nodes label. (see OnBeforeEdit and OnAfterEdit sub for what happens before and after the user edits the label)
                    EnableNodeSelection = true;
                    return;

                    //if they clicked on something different to what was already selected -> change the selection
                }
                else
                {
                    SelectedPaths.Clear();
                    //get rid of existing selected paths
                    SelectedPaths.Add(GetPathFromNode(ClickedNode));
                    //add new path to selected paths
                    PreviousNode = ClickedNode;
                    //store clicked node as the previously clicked on node (used for Shift button)
                }
            }


            //Finish off

            Controller.SelectedPaths = SelectedPaths;
            //update the selected paths "in the controller"


            //Let the user click on other nodes again

            EnableNodeSelection = true;
        }
Esempio n. 45
0
        /// <summary>
        /// 解析导航规则
        /// </summary>
        /// <param name="startingUrl">起始地址</param>
        /// <returns>导航地址</returns>
        private StringCollection ParseNavigationRuleItem(StringCollection startingUrl)
        {
            StringCollection urls = new StringCollection();

            foreach (string u in startingUrl)
            {
                foreach (NavigationRule rule in _urlItem.NavigationRules)
                {
                    /*
                     * 描述:
                     * 加入最终页面地址
                     *
                     * 步骤:
                     * 1.判断是否终端页面地址,如果是则直接加入并引发事件.
                     * 2.否则,请求web服务器并返回html文本,根据导航规则解析出终端页面地址.
                     *
                     * 修改标志:王亚 201204244
                     */
                    if (rule.Terminal)
                    {
                        urls.Add(u);                                //最终页面直接加入导航地址
                        if (onSingleComplete != null)
                        {
                            this.onSingleComplete(this, u);         //引发增加一条网址事件
                        }
                    }
                    else
                    {
                        try
                        {
                            HttpHelper http = new HttpHelper();

                            /*
                             *修改标志 20120601 王亚 解析导航地址时增加Http请求编码
                             */
                            http._encoding = Encoding.GetEncoding(_urlItem.UrlEncoding);
                            string           htmlText   = http.RequestResult(u); //发送Http请求获取导航地址
                            StringCollection navUrlItem = ParseNavigationRuleHtmlText(rule, htmlText);
                            foreach (string r in navUrlItem)
                            {
                                /*
                                 * 处理相对路径网址问题如:/html/gndy/jddy/20120425/37418.html
                                 * 如果不包含http://选项,则在相对路径前边加上主机地址。
                                 */
                                string path = r;
                                if (!r.Contains("http://") && r.Length > 0)
                                {
                                    path = r.Insert(0, "http://" + http.WebResponse.ResponseUri.Authority);
                                }
                                urls.Add(path);
                                if (onSingleComplete != null)
                                {
                                    this.onSingleComplete(this, path);    //引发增加一条网址事件
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (OnAppendSingileLog != null)
                            {
                                OnAppendSingileLog(this, new LogEventArgs(ex.Message));
                            }
                        }
                    }
                }
            }

            return(urls);
        }
    public virtual bool runTest()
    {
        Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer);
        int              iCountErrors    = 0;
        int              iCountTestcases = 0;
        String           strLoc          = "Loc_000oo";
        StringCollection sc;
        StringEnumerator en;
        string           curr;
        bool             res;

        string [] values =
        {
            "a",
            "aa",
            "",
            " ",
            "text",
            "     spaces",
            "1",
            "$%^#",
            "2222222222222222222222222",
            System.DateTime.Today.ToString(),
            Int32.MaxValue.ToString()
        };
        try
        {
            Console.WriteLine("--- create collection ---");
            strLoc = "Loc_001oo";
            iCountTestcases++;
            sc = new StringCollection();
            Console.WriteLine("1. Reset() on empty collection");
            Console.WriteLine("     - Reset()");
            iCountTestcases++;
            en = sc.GetEnumerator();
            try
            {
                en.Reset();
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0001a, unexpected exception: " + e.ToString());
            }
            Console.WriteLine("     - Current");
            iCountTestcases++;
            try
            {
                curr = en.Current;
                iCountErrors++;
                Console.WriteLine("Err_0001b, no exception");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("  expected exception: " + ex.Message);
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0001c, unexpected exception: {0}", e.ToString());
            }
            Console.WriteLine("     - Add item to the collection");
            iCountTestcases++;
            int cnt = sc.Count;
            sc.Add(values[0]);
            if (sc.Count != 1)
            {
                iCountErrors++;
                Console.WriteLine("Err_0001d, failed to add item");
            }
            Console.WriteLine("     - Reset() on modified collection");
            try
            {
                en.Reset();
                iCountErrors++;
                Console.WriteLine("Err_0001e, no exception");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("  expected exception: " + ex.Message);
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0001f, unexpected exception: {0}", e.ToString());
            }
            Console.WriteLine("2. Reset() on filled collection");
            strLoc = "Loc_002oo";
            iCountTestcases++;
            sc.AddRange(values);
            en = sc.GetEnumerator();
            Console.WriteLine("     - Reset() after Reset()");
            iCountTestcases++;
            try
            {
                en.Reset();
                en.Reset();
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002a, unexpected exception: " + e.ToString());
            }
            Console.WriteLine("     - Reset() after 0th item ");
            iCountTestcases++;
            if (!en.MoveNext())
            {
                iCountErrors++;
                Console.WriteLine("Err_0002b, MoveNext() returned false");
            }
            iCountTestcases++;
            curr = en.Current;
            if (String.Compare(curr, values[0], false) != 0)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002c, Current returned wrong value");
            }
            en.Reset();
            if (!en.MoveNext())
            {
                iCountErrors++;
                Console.WriteLine("Err_0002d, MoveNext() returned false");
            }
            iCountTestcases++;
            if (String.Compare(en.Current, curr, false) != 0)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002e, Current returned wrong value");
            }
            int ind = sc.Count / 2;
            Console.WriteLine("     - Reset() after {0} item ", ind);
            en.Reset();
            for (int i = 0; i < ind + 1; i++)
            {
                iCountTestcases++;
                res = en.MoveNext();
                if (!res)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_0002f_{0}, MoveNext returned false", i);
                }
                iCountTestcases++;
                curr = en.Current;
                if (String.Compare(curr, sc[i], false) != 0)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_0002g_{0}, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i]);
                }
                iCountTestcases++;
                string curr1 = en.Current;
                if (String.Compare(curr, curr1, false) != 0)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_0002h_{0}, second call of Current returned different result", i);
                }
            }
            en.Reset();
            if (!en.MoveNext())
            {
                iCountErrors++;
                Console.WriteLine("Err_0002i, MoveNext() returned false");
            }
            iCountTestcases++;
            if (String.Compare(en.Current, sc[0], false) != 0)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002j, Current returned wrong value");
            }
            ind = sc.Count;
            Console.WriteLine("     - Reset() after {0} item ", ind - 1);
            en.Reset();
            for (int i = 0; i < ind; i++)
            {
                iCountTestcases++;
                res = en.MoveNext();
                if (!res)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_0002k_{0}, MoveNext returned false", i);
                }
                iCountTestcases++;
                curr = en.Current;
                if (String.Compare(curr, sc[i], false) != 0)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_0002l_{0}, Current returned \"{1}\" instead of \"{2}\"", i, curr, sc[i]);
                }
                iCountTestcases++;
                string curr1 = en.Current;
                if (String.Compare(curr, curr1, false) != 0)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_0002m_{0}, second call of Current returned different result", i);
                }
            }
            en.Reset();
            if (!en.MoveNext())
            {
                iCountErrors++;
                Console.WriteLine("Err_0002n, MoveNext() returned false");
            }
            iCountTestcases++;
            if (String.Compare(en.Current, sc[0], false) != 0)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002o, Current returned wrong value");
            }
            en.Reset();
            Console.WriteLine("     - Reset() after enumerated beyond the last item");
            for (int i = 0; i < ind; i++)
            {
                res = en.MoveNext();
            }
            res = en.MoveNext();
            iCountTestcases++;
            res = en.MoveNext();
            if (res)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002p, MoveNext returned true");
            }
            en.Reset();
            if (!en.MoveNext())
            {
                iCountErrors++;
                Console.WriteLine("Err_0002q, MoveNext() returned false");
            }
            iCountTestcases++;
            if (String.Compare(en.Current, sc[0], false) != 0)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002r, Current returned wrong value");
            }
            Console.WriteLine("     - Current after Reset()");
            iCountTestcases++;
            en.Reset();
            try
            {
                curr = en.Current;
                iCountErrors++;
                Console.WriteLine("Err_0002s, no exception");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("  expected exception: " + ex.Message);
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0002t, unexpected exception: {0}", e.ToString());
            }
            Console.WriteLine("3. Reset() modified collection in process of enumeration");
            strLoc = "Loc_003oo";
            iCountTestcases++;
            if (sc.Count < 1)
            {
                sc.AddRange(values);
            }
            iCountTestcases++;
            en = sc.GetEnumerator();
            Console.WriteLine("     - Reset() for init position of the enumerator");
            sc.RemoveAt(0);
            iCountTestcases++;
            try
            {
                en.Reset();
                iCountErrors++;
                Console.WriteLine("Err_0003a, no exception");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("  expected exception: " + ex.Message);
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0003b, unexpected exception: {0}", e.ToString());
            }
            en = sc.GetEnumerator();
            Console.WriteLine("     - Enumerate to the middle of the collection and Reset()");
            for (int i = 0; i < sc.Count / 2; i++)
            {
                iCountTestcases++;
                res = en.MoveNext();
            }
            Console.WriteLine("     - modify collection");
            curr = en.Current;
            iCountTestcases++;
            sc.RemoveAt(0);
            Console.WriteLine("     - get Current");
            iCountTestcases++;
            if (String.Compare(curr, en.Current) != 0)
            {
                iCountErrors++;
                Console.WriteLine("Err_0003c, current returned {0} instead of {1}", en.Current, curr);
            }
            Console.WriteLine("     - call Reset()");
            iCountTestcases++;
            try
            {
                en.Reset();
                iCountErrors++;
                Console.WriteLine("Err_0003d, no exception");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("  expected exception: " + ex.Message);
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0003e, unexpected exception: {0}", e.ToString());
            }
            en = sc.GetEnumerator();
            Console.WriteLine("     - Enumerate to end of the collection and Reset()");
            for (int i = 0; i < sc.Count; i++)
            {
                iCountTestcases++;
                res = en.MoveNext();
            }
            Console.WriteLine("     - modify collection");
            iCountTestcases++;
            sc.RemoveAt(0);
            Console.WriteLine("     - call Reset()");
            iCountTestcases++;
            try
            {
                en.Reset();
                iCountErrors++;
                Console.WriteLine("Err_0003f, no exception");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("  expected exception: " + ex.Message);
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0003g, unexpected exception: {0}", e.ToString());
            }
            Console.WriteLine("4. Reset() after enumerating beyond the end");
            strLoc = "Loc_004oo";
            iCountTestcases++;
            if (sc.Count < 1)
            {
                sc.AddRange(values);
            }
            iCountTestcases++;
            en = sc.GetEnumerator();
            Console.WriteLine("     - Enumerate through the collection");
            for (int i = 0; i < sc.Count; i++)
            {
                iCountTestcases++;
                res = en.MoveNext();
            }
            Console.WriteLine("     - Enumerate beyond the end");
            res = en.MoveNext();
            if (res)
            {
                iCountErrors++;
                Console.WriteLine("Err_0004a, MoveNext returned true after moving beyond the end");
            }
            Console.WriteLine("     - modify collection");
            cnt = sc.Count;
            iCountTestcases++;
            sc.RemoveAt(0);
            if (sc.Count != cnt - 1)
            {
                iCountErrors++;
                Console.WriteLine("Err_0004b, didn't remove 0-item");
            }
            Console.WriteLine("     - call Reset()");
            iCountTestcases++;
            try
            {
                en.Reset();
                iCountErrors++;
                Console.WriteLine("Err_0004c, no exception");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("  expected exception: " + ex.Message);
            }
            catch (Exception e)
            {
                iCountErrors++;
                Console.WriteLine("Err_0004d, unexpected exception: {0}", e.ToString());
            }
        }
        catch (Exception exc_general)
        {
            ++iCountErrors;
            Console.WriteLine(s_strTFAbbrev + " : Error Err_general!  strLoc==" + strLoc + ", exc_general==\n" + exc_general.ToString());
        }
        if (iCountErrors == 0)
        {
            Console.WriteLine("Pass.   " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases);
            return(true);
        }
        else
        {
            Console.WriteLine("Fail!   " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums);
            return(false);
        }
    }
Esempio n. 47
0
        private void RunBuild(FileInfo buildFile)
        {
            Log(Level.Info, "{0} {1}", buildFile.FullName, DefaultTarget);

            // create new project with same threshold as current project and
            // increased indentation level, and initialize it using the same
            // configuration node
            Project project = CreateProject(buildFile);

            // have the new project inherit properties from the current project
            if (InheritAll)
            {
                StringCollection excludes = new StringCollection();
                excludes.Add(NAntPropertyFileName);
                excludes.Add(NAntPropertyLocation);
                excludes.Add(NAntPropertyOnSuccess);
                excludes.Add(NAntPropertyOnFailure);
                excludes.Add(NAntPropertyProjectBaseDir);
                excludes.Add(NAntPropertyProjectBuildFile);
                excludes.Add(NAntPropertyProjectDefault);
                excludes.Add(NAntPropertyProjectName);
                excludes.Add(NAntPropertyVersion);
                project.Properties.Inherit(Properties, excludes);
            }

            // add/overwrite properties
            foreach (PropertyTask property in OverrideProperties)
            {
                // expand properties in context of current project for non-dynamic
                // properties
                if (!property.Dynamic)
                {
                    property.Value = Project.ExpandProperties(property.Value, Location);
                }
                property.Project = project;
                property.Execute();
            }

            if (InheritRefs)
            {
                // pass datatypes thru to the child project
                project.DataTypeReferences.Inherit(Project.DataTypeReferences);
            }

            // handle multiple targets
            if (DefaultTarget != null)
            {
                foreach (string t in DefaultTarget.Split(' '))
                {
                    string target = t.Trim();
                    if (target.Length > 0)
                    {
                        project.BuildTargets.Add(target);
                    }
                }
            }

            try
            {
                // run the given build
                if (!project.Run())
                {
                    throw new BuildException("Nested build failed.  Refer to build log for exact reason.");
                }
            }
            finally
            {
                if (PassByRef.Length > 0)
                {
                    foreach (string p in PassByRef.Split(' '))
                    {
                        if (p != null)
                        {
                            string property = p.Trim();
                            if (property.Length > 0 && project.Properties[property] != null)
                            {
                                Properties[property] = project.Properties[property];
                            }
                        }
                    }
                }
            }
        }
Esempio n. 48
0
        /// <summary>
        /// Event handler for the DragDrop event.
        /// </summary>
        /// <param name="sender">
        /// The source control, emitting the event.
        /// </param>
        /// <param name="e">
        /// Event arguments describing the circumstances of the event.
        /// </param>
        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            // Already running?
            if ((processThread != null) && processThread.IsAlive)
            {
                return;
            }

            // Handle FileDrop data:
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // Assign the file names to a string array, in  case the user has selected multiple files:
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                Array.Sort(files);
                try
                {
                    // Loop through files and compose a list with all presets to process:
                    processFiles = new StringCollection();
                    for (int i = 0; i < files.Length; i++)
                    {
                        try
                        {
                            // Is a directory?
                            if (Directory.Exists(files[i]))
                            {
                                // Search for files:
                                string[] newFiles = Directory.GetFiles(files[i], "*.vstpreset", SearchOption.AllDirectories);
                                if (newFiles != null)
                                {
                                    processFiles.AddRange(newFiles);
                                }
                            }

                            // Is a *.preset file?
                            else if (string.Compare(Path.GetExtension(files[i]), ".vstpreset", true) == 0)
                            {
                                // Add it:
                                processFiles.Add(files[i]);
                            }
                        }
                        catch
                        {
                        }
                    }

                    // Found anything?
                    if (processFiles.Count == 0)
                    {
                        return;
                    }

                    // The sending application (drop source) is still waiting for us to
                    // finish the drag and drop operation. We thus create a working thread
                    // and delegate the hard work to this thread:
                    processThread = new Thread((ThreadStart) delegate() { Invoke((MethodInvoker) delegate() { ProcessFunc(); }); });
                    processThread.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
        public IDictionary ToCodeDom()
        {
            Hashtable codeNs = new Hashtable();

            // namespaces
            foreach (NamespaceDeclaration ns in this.namespaces.Values)
            {
                foreach (DictionaryEntry de in ns.ToCodeDom())
                {
                    codeNs.Add(de.Key, de.Value);
                }
            }

            // classes
            foreach (ClassDeclaration c in this.classes.Values)
            {
                CodeNamespace ns = new CodeNamespace(this.Name);

                c.ToCodeDom(ns.Types);

                StringCollection usings = new StringCollection();
                foreach (String s in this.Imports)
                {
                    usings.Add(s);
                }
                foreach (String import in c.Imports)
                {
                    if (!usings.Contains(import))
                    {
                        usings.Add(import);
                    }
                }
                // imports
                foreach (String import in usings)
                {
                    ns.Imports.Add(new CodeNamespaceImport(import));
                }

                codeNs.Add(
                    new FileName(this.FullName, c.Name),
                    ns);
            }

            // enums
            foreach (EnumDeclaration e in this.enums.Values)
            {
                CodeNamespace ns = new CodeNamespace(this.Name);

                ns.Types.Add((CodeTypeDeclaration)e.ToCodeDom());

                StringCollection usings = new StringCollection();
                foreach (String s in this.imports)
                {
                    usings.Add(s);
                }
                foreach (String import in usings)
                {
                    ns.Imports.Add(new CodeNamespaceImport(import));
                }

                codeNs.Add(
                    new FileName(this.FullName, e.Name),
                    ns);
            }


            return(codeNs);
        }
Esempio n. 50
0
        private void cmdLogin_Click(object sender, EventArgs e)
        {
            try
            {
                EnableUI(false);
                if (!scSites.Contains(cboSites.Text))
                {
                    scSites.Add(cboSites.Text);
                }
                LoginContext = new Microsoft.SharePoint.Client.ClientContext(cboSites.Text);
                SecureString password = GetSecureString(txtPassword.Text);



                switch (GetAuthMode())

                {
                case "Basic":
                    if (!string.IsNullOrEmpty(txtDomain.Text))
                    {
                        LoginContext.Credentials = new NetworkCredential(txtUserName.Text, txtPassword.Text, txtDomain.Text);
                    }
                    else
                    {
                        LoginContext.Credentials = new NetworkCredential(txtUserName.Text, txtPassword.Text);
                    }
                    break;

                case "SPO":

                    LoginContext.Credentials = new spc.SharePointOnlineCredentials(txtUserName.Text, password);
                    break;

                case "PNP":

                    OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
                    ClientContext ctx = authManager.GetWebLoginClientContext(cboSites.Text);
                    //ClientContext context = authManager.GetSharePointOnlineAuthenticatedContextTenant(cboSites.Text, txtUserName.Text,password);
                    break;

                default:

                    break;
                }

                LoginContext.ExecutingWebRequest += delegate(object sender2, WebRequestEventArgs e2)
                {
                    e2.WebRequestExecutor.WebRequest.UserAgent = "NONISV|RammWare|spToolbelt2019/1.0";
                };

                spc.Web oRootWeb = LoginContext.Site.RootWeb;
                LoginContext.Load(oRootWeb);
                LoginContext.ExecuteQuery();
                System.Diagnostics.Trace.WriteLine(oRootWeb.Title);
                UserLoggedIn = true;
                SaveSettings();
            }
            catch (Exception ex)
            {
                ErrorHandling.LogError(ex, "frmLogin.cmdLogin_Click", "");
            }
        }
Esempio n. 51
0
		/// <summary>
		/// return the all leaf categories
		/// </summary>
		/// <param name="parentCategoryID"></param>
		/// <param name="categoryTypeCollection"></param>
		/// <returns></returns>
		private static  bool getAllSubCategories(int parentCategoryID,ApiContext apiContext,out CategoryTypeCollection categoryTypeCollection,out string message)
		{
			//basic init
			GetCategoriesCall api = new GetCategoriesCall(apiContext);
			setBasicInfo(ref api);
			//return all childs categories
			StringCollection parent=new StringCollection();
			parent.Add(parentCategoryID.ToString());
			api.CategoryParent=parent;
			api.ViewAllNodes=true;
			api.LevelLimit=10;
			categoryTypeCollection=null;
			message=string.Empty;
			
			try
			{
				//call
				categoryTypeCollection = api.GetCategories();
			}
			catch(Exception e)
			{
				message=e.Message;
				return false;
			}
			
			return true;
		}
        private int EvaluarBoolSp(string tipoArchivo, Regla regla, int x, int exitoLinea, string text)
        {
            //en la tabla regla de archivos se agrego una columna forma de validacion los cuales son:
            //1 = Valida el dato en la aplicacion
            //0 = Consulta los stores respectivos
            StringCollection resultadoValor = new StringCollection();

            if (regla.FormaValidacion == 1)
            {
                string resultado = string.Empty;
                switch (regla.ReglaValidacion.Trim())
                {
                case "pa_valida_Fecha @valor":
                    resultado = paValidaFecha(CampoActual).ToString();
                    break;

                case "pa_valida_Numero7x2 @valor":
                    resultado = paValidaNumero7x2(CampoActual).ToString();
                    break;

                case "pa_valida_SoloNumeros @valor":
                    resultado = paValidaSoloNumero(CampoActual).ToString();
                    break;
                }
                resultadoValor.Add(resultado);
            }
            else
            {
                var valor = regla.ReglaValidacion;

                if (valor.Contains("pa_valida_SumaDetalleEnTotal"))
                {
                    return(EvaluarBoolSumaDetalleEnTotal(regla));
                }
                if (valor.Contains("pa_valida_montoWithKeyNomina"))
                {
                    valor = valor.Replace("@IdArchivo", IdArchivo.ToString());
                    valor = valor.Replace("@monto", CampoActual);
                    valor = valor.Replace("@keyNomina", string.Format("'{0}'", text.Trim().Substring(31, 25)));
                }
                else
                {
                    valor = valor.Replace("@valor", "'" + CampoActual + "'");
                    valor = valor.Replace("@IdArchivo", IdArchivo.ToString());
                    valor = valor.Replace("@NumeroLinea", (x + 1).ToString());
                    valor = valor.Replace("@CampoInicial", regla.CaracterInicial.ToString());
                    valor = valor.Replace("@LargoCampo", regla.LargoCampo.ToString());
                }

                using (var context = new DISEntities())
                {
                    var resultado = context.pa_valida_EjecutaProcedimientoAlmacenado(valor);
                    resultadoValor = ObtieneColeccion(resultado);
                }
            }

            if (resultadoValor[0] == "1")
            {
                exitoLinea = 1;
                //start:
                //1.- valida que exista una PRIMAPAG
                if (tipoArchivo == "PRIMDCUA")
                {
                    if (tipoArchivo == "PRIMDCUA")
                    {
                        exitoLinea = EvaluarBoolSpPrimaPag(regla, exitoLinea);
                    }
                }
                //end
            }
            else
            {
                ContadorErrores = ContadorErrores + 1;
                exitoLinea      = 0;
            }
            return(exitoLinea);
        }
Esempio n. 53
0
 public virtual bool runTest()
 {
     Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver: " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     IntlStrings intl;
     String strLoc = "Loc_000oo";
     StringCollection sc; 
     string [] values = 
     {
         "",
         " ",
         "a",
         "aa",
         "text",
         "     spaces",
         "1",
         "$%^#",
         "2222222222222222222222222",
         System.DateTime.Today.ToString(),
         Int32.MaxValue.ToString()
     };
     int cnt = 0;            
     try
     {
         intl = new IntlStrings(); 
         Console.WriteLine("--- create collection ---");
         strLoc = "Loc_001oo"; 
         iCountTestcases++;
         sc = new StringCollection();
         Console.WriteLine("1. Check for empty collection");
         for (int i = 0; i < values.Length; i++) 
         {
             iCountTestcases++;
             if (sc.IndexOf(values[i]) != -1) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0001_{0}, returned {1} for empty collection", i, sc.IndexOf(values[i]));
             }
         } 
         Console.WriteLine("2. add simple strings and verify IndexOf()");
         strLoc = "Loc_002oo"; 
         iCountTestcases++;
         cnt = sc.Count;
         sc.AddRange(values);
         if (sc.Count != values.Length) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0002a, count is {0} instead of {1}", sc.Count, values.Length);
         } 
         for (int i = 0; i < values.Length; i++) 
         {
             iCountTestcases++;
             if (sc.IndexOf(values[i]) != i) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0002_{0}b, IndexOf returned {1} instead of {0}", i, sc.IndexOf(values[i]));
             } 
         }
         Console.WriteLine("3. add intl strings and verify IndexOf()");
         strLoc = "Loc_003oo"; 
         string [] intlValues = new string [values.Length];
         for (int i = 0; i < values.Length; i++) 
         {
             string val = intl.GetString(MAX_LEN, true, true, true);
             while (Array.IndexOf(intlValues, val) != -1 )
                 val = intl.GetString(MAX_LEN, true, true, true);
             intlValues[i] = val;
         } 
         int len = values.Length;
         Boolean caseInsensitive = false;
         for (int i = 0; i < len; i++) 
         {
             if(intlValues[i].Length!=0 && intlValues[i].ToLower()==intlValues[i].ToUpper())
                 caseInsensitive = true;
         }
         iCountTestcases++;
         cnt = sc.Count;
         sc.AddRange(intlValues);
         if ( sc.Count != (cnt + intlValues.Length) ) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0003a, count is {0} instead of {1}", sc.Count, cnt + intlValues.Length);
         } 
         for (int i = 0; i < intlValues.Length; i++) 
         {
             iCountTestcases++;
             if (sc.IndexOf(intlValues[i]) != values.Length + i) 
             {
                 iCountErrors++;
                 Console.WriteLine("Err_0003_{0}b, IndexOf returned {1} instead of {2}", i, sc.IndexOf(intlValues[i]), values.Length + i);
             } 
         }
         Console.WriteLine("4. duplicate strings ");
         strLoc = "Loc_004oo"; 
         iCountTestcases++;
         sc.Clear();
         string intlStr = intlValues[0];
         sc.Add(intlStr);        
         sc.AddRange(values);
         sc.AddRange(intlValues);        
         cnt = values.Length + 1 + intlValues.Length;
         if (sc.Count != cnt) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0004a, count is {1} instead of {2}", sc.Count, cnt);
         } 
         iCountTestcases++;
         if (sc.IndexOf(intlStr) != 0) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0004b, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), 0);
         }
         iCountTestcases++;
         sc.Clear();
         sc.AddRange(values);
         sc.AddRange(intlValues);        
         sc.Add(intlStr);        
         cnt = values.Length + 1 + intlValues.Length;
         if (sc.Count != cnt) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0004c, count is {1} instead of {2}", sc.Count, cnt);
         } 
         iCountTestcases++;
         if (sc.IndexOf(intlStr) != values.Length) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0004b, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), values.Length);
         }
         Console.WriteLine("5. Case sensitivity");
         strLoc = "Loc_005oo"; 
         iCountTestcases++;
         sc.Clear();
         sc.Add(intlValues[0].ToUpper());
         sc.AddRange(values);
         sc.Add(intlValues[0].ToLower());
         cnt = values.Length + 2;
         if (sc.Count != cnt) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0005, count is {1} instead of {2} ", sc.Count, cnt);
         } 
         intlStr = intlValues[0].ToLower();
         iCountTestcases++;
         Console.WriteLine(" - look for lowercase" );
         if (!caseInsensitive && (sc.IndexOf(intlStr) != values.Length  + 1)) 
         {
             iCountErrors++;
             Console.WriteLine("Err_0005a, IndexOf() returned {0} instead of {1} ", sc.IndexOf(intlStr), values.Length  + 1);
         }
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_general!  strLoc=="+ strLoc +", exc_general==\n"+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "Pass.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
         return true;
     }
     else
     {
         Console.WriteLine("Fail!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
Esempio n. 54
0
        public void Compile(string nss,
                            ValidationEventHandler h, XmlSchema schema)
        {
            if (SkipCompile)
            {
                return;                 // used by XmlSchemaAny.AnyTypeContent.
            }
            Reset();
            int    nscount         = 0;
            string actualNamespace = nss == null ? "##any" : nss;

            string[] nslist = XmlSchemaUtil.SplitList(actualNamespace);
            for (int i = 0; i < nslist.Length; i++)
            {
                string ns = nslist [i];
                switch (ns)
                {
                case "##any":
                    if (HasValueAny)
                    {
                        xsobj.error(h, "Multiple specification of ##any was found.");
                    }
                    nscount    |= 1;
                    HasValueAny = true;
                    break;

                case "##other":
                    if (HasValueOther)
                    {
                        xsobj.error(h, "Multiple specification of ##other was found.");
                    }
                    nscount      |= 2;
                    HasValueOther = true;
                    break;

                case "##targetNamespace":
                    if (HasValueTargetNamespace)
                    {
                        xsobj.error(h, "Multiple specification of ##targetNamespace was found.");
                    }
                    nscount |= 4;
                    HasValueTargetNamespace = true;
                    break;

                case "##local":
                    if (HasValueLocal)
                    {
                        xsobj.error(h, "Multiple specification of ##local was found.");
                    }
                    nscount      |= 8;
                    HasValueLocal = true;
                    break;

                default:
                    if (!XmlSchemaUtil.CheckAnyUri(ns))
                    {
                        xsobj.error(h, "the namespace is not a valid anyURI");
                    }
                    else if (ResolvedNamespaces.Contains(ns))
                    {
                        xsobj.error(h, "Multiple specification of '" + ns + "' was found.");
                    }
                    else
                    {
                        nscount |= 16;
                        ResolvedNamespaces.Add(ns);
                    }
                    break;
                }
            }
            if ((nscount & 1) == 1 && nscount != 1)
            {
                xsobj.error(h, "##any if present must be the only namespace attribute");
            }
            if ((nscount & 2) == 2 && nscount != 2)
            {
                xsobj.error(h, "##other if present must be the only namespace attribute");
            }
        }
Esempio n. 55
0
    public static void Optimize(ArrayList list)
    {
        for (int i = 1; i < list.Count; i++)
        {
            X86Code x0 = list[i] as X86Code;
            if (x0 == null || x0.ignore || x0.IsBrTarget) continue;

            ArrayList listx = new ArrayList();
            listx.Add(x0);
            for (int j = 1;; j++)
            {
                X86Code xx = GetPrevious(list, i, j);
                if (xx == null) break;
                listx.Add(xx);
            }
            if (listx.Count < 2) continue;

            X86Code[] x = listx.ToArray(typeof(X86Code)) as X86Code[];
            if (IsMovEtc(x[0].Mnemonic) && !IsXS(x[0].Operand1) && IsXX(x[0].Operand2) && x[0].Operand1 != x[0].Operand2)
            {
                for (int j = 1; j < x.Length; j++)
                {
                    if (x[j].Mnemonic == "mov" && x[j].Operand1 == x[0].Operand2 && !IsXS(x[j].Operand2)
                        && !(IsAddr(x[0].Operand1) && IsAddr(x[j].Operand2)))
                    {
                        if (x[0].Operand1 != x[j].Operand2 && (IsXX(x[0].Operand1) || IsXX(x[j].Operand2)))
                        {
                            x[j].Ignore();
                            x[0].Ignore();
                            X86Code xx = new X86Code(x[0].Mnemonic, x[0].Operand1, x[j].Operand2);
                            xx.Notes = "[optimize] add";
                            list.Insert(i + 1, xx);
                        }
                    }
                    else if (IsMovEtc(x[j].Mnemonic) && x[j].Operand1 != x[0].Operand2)
                    {
                        continue;
                    }
                    break;
                }
                if (x[0].ignore) continue;
            }
            switch (x[0].Mnemonic)
            {
                case "pop":
                {
                    Hashtable t = new Hashtable();
                    for (int j = 1; j < x.Length; j++)
                    {
                        if (x[j].Mnemonic == "push")
                        {
                            if (!t.Contains(x[j].Operand1))
                            {
                                if (x[j].Operand1 == x[0].Operand1)
                                {
                                    x[j].Ignore();
                                    x[0].Ignore();
                                }
                                else if (IsXX(x[j].Operand1) || IsXX(x[0].Operand1))
                                {
                                    x[j].Ignore();
                                    x[0].Ignore();
                                    X86Code xx = new X86Code("mov", x[0].Operand1, x[j].Operand1);
                                    xx.Notes = "[optimize] add";
                                    list.Insert(i + 1, xx);
                                }
                            }
                            else if (!t.Contains(x[0].Operand1))
                            {
                                if (IsXX(x[j].Operand1) || IsXX(x[0].Operand1))
                                {
                                    x[j].Ignore();
                                    x[0].Ignore();
                                    X86Code xx = new X86Code("mov", x[0].Operand1, x[j].Operand1);
                                    xx.Notes = "[optimize] add";
                                    i = list.IndexOf(x[j]);
                                    list.Insert(i + 1, xx);
                                }
                            }
                        }
                        else if (IsMovEtc(x[j].Mnemonic))
                        {
                            t[x[j].Operand1] = true;
                            continue;
                        }
                        break;
                    }
                    break;
                }
                case "cmp":
                    if (IsXX(x[0].Operand1) && IsDigit(x[0].Operand2))
                    {
                        for (int j = 1; j < x.Length; j++)
                        {
                            if (x[j].Mnemonic == "mov" && x[j].Operand1 == x[0].Operand1)
                            {
                                x[j].Ignore();
                                x[0].Ignore();
                                X86Code xx = new X86Code("cmp", x[j].Operand2, x[0].Operand2);
                                xx.Notes = "[optimize] add";
                                list.Insert(i + 1, xx);
                            }
                            else if (IsMovEtc(x[j].Mnemonic) && x[j].Operand1 != x[0].Operand1)
                            {
                                continue;
                            }
                            break;
                        }
                    }
                    break;
                case "je":
                case "jne":
                case "jz":
                case "jnz":
                    if (x[1].Mnemonic == "cmp" && IsXX(x[1].Operand1) && !IsDigit(x[1].Operand2))
                    {
                        for (int j = 2; j < x.Length; j++)
                        {
                            if (x[j].Mnemonic == "mov" && x[j].Operand1 == x[1].Operand1)
                            {
                                x[j].Ignore();
                                x[1].Ignore();
                                X86Code xx = new X86Code("cmp", x[1].Operand2, x[j].Operand2);
                                xx.Notes = "[optimize] add";
                                i = list.IndexOf(x[1]);
                                list.Insert(i + 1, xx);
                            }
                            else if (IsMovEtc(x[j].Mnemonic) && x[j].Operand1 != x[1].Operand1)
                            {
                                continue;
                            }
                            break;
                        }
                    }
                    break;
                case "mov":
                    if (x.Length > 2 && IsAddEtc(x[1].Mnemonic) && x[2].Mnemonic == "mov"
                        && x[0].Operand2 == x[1].Operand1 && x[1].Operand1 == x[2].Operand1)
                    {
                        if (x[1].Mnemonic == "inc" || x[1].Mnemonic == "dec")
                        {
                            x[2].Ignore();
                            x[1].Ignore();
                            x[0].Ignore();
                            X86Code xx = new X86Code(x[1].Mnemonic, x[0].Operand1);
                            xx.Notes = "[optimize] add";
                            list.Insert(i + 1, xx);
                        }
                        else if (x[0].Operand1 == x[1].Operand2 && !IsAddr(x[2].Operand2))
                        {
                            x[2].Ignore();
                            x[1].Ignore();
                            x[0].Ignore();
                            X86Code xx = new X86Code(x[1].Mnemonic, x[0].Operand1, x[2].Operand2);
                            xx.Notes = "[optimize] add";
                            list.Insert(i + 1, xx);
                        }
                        else if (x[0].Operand1 == x[2].Operand2 && !IsAddr(x[1].Operand2))
                        {
                            x[2].Ignore();
                            x[1].Ignore();
                            x[0].Ignore();
                            X86Code xx = new X86Code(x[1].Mnemonic, x[0].Operand1, x[1].Operand2);
                            xx.Notes = "[optimize] add";
                            list.Insert(i + 1, xx);
                        }
                    }
                    break;
                case "add":
                    if (x[0].Operand2 == "1")
                    {
                        x[0].Ignore();
                        X86Code xx = new X86Code("inc", x[0].Operand1);
                        xx.Notes = "[Optimize] add";
                        list.Insert(i + 1, xx);
                    }
                    break;
                case "sub":
                    if (x[0].Operand2 == "1")
                    {
                        x[0].Ignore();
                        X86Code xx = new X86Code("dec", x[0].Operand1);
                        xx.Notes = "[Optimize] add";
                        list.Insert(i + 1, xx);
                    }
                    break;
            }
        }

        StringCollection jmp = new StringCollection();
        for (int i = 0; i < list.Count; i++)
        {
            X86Code x = list[i] as X86Code;
            if (x == null || x.ignore) continue;

            if (x.Mnemonic == "mov" && X86Code.IsXX(x.Operand1) && x.Operand2 == "0")
            {
                x.Ignore();
                X86Code xx = new X86Code("xor", x.Operand1, x.Operand1);
                xx.Notes = "[optimize] add";
                list.Insert(i + 1, xx);
            }
            else if (x.Mnemonic == "mov" && x.Operand1 == x.Operand2)
            {
                x.Ignore();
            }
            else if (x.Mnemonic.StartsWith("j"))
            {
                jmp.Add(x.Operand1);
            }
        }
        for (int i = 0; i < list.Count; i++)
        {
            X86Code x = list[i] as X86Code;
            if (x == null) continue;

            if (x.IsBrTarget && !jmp.Contains(x.Label)) x.IsBrTarget = false;
        }
    }
Esempio n. 56
0
        public void ExecuteSQLonTarget(TargetServerInfo targetServer, AsyncUpdateStatus updateStatus, AsyncQueueBCPJob queueBCPJob, string sqlToExecute)
        {
            DateTime dtStart = DateTime.Now;
            AsyncNotificationEventArgs eventArgs         = new AsyncNotificationEventArgs(NotificationEventFunctionCode.ExecuteSqlOnAzure, 0, "", CommonFunc.FormatString(Properties.Resources.ProcessStarted, dtStart.ToString(), dtStart.ToUniversalTime().ToString()) + Environment.NewLine, Color.DarkSlateBlue);
            StringCollection           strColl           = new StringCollection();
            StringCollection           bcpUploadCommands = new StringCollection();
            bool inBCPCommand = false;
            int  idx          = 0;

            AsyncProcessingStatus.FinishedProcessingJobs = true;

            updateStatus(eventArgs);

            string connectionStr = targetServer.ConnectionStringTargetDatabase;

            CommentAreaHelper cah = new CommentAreaHelper();

            try
            {
                cah.FindCommentAreas(sqlToExecute);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            long lCharCnt      = 0;
            int  sqlCmdLoopCtr = 0;

            AsyncProcessingStatus.NumberOfCommands         = 0;
            AsyncProcessingStatus.NumberOfCommandsExecuted = 0;

            if (cah.Lines.Count() > 0)
            {
                foreach (string line in cah.Lines)
                {
                    if (line.StartsWith(Properties.Resources.Go) && !cah.IsIndexInComments(lCharCnt))
                    {
                        AsyncProcessingStatus.NumberOfCommands++;
                    }
                    lCharCnt += line.Length + cah.CrLf;
                }
            }

            using (SqlConnection con = new SqlConnection(connectionStr))
            {
                StringBuilder    sql           = new StringBuilder(5000);
                StringCollection sqlDepends    = new StringCollection();
                string           currentObject = "";
                bool             comment       = false;

                try
                {
                    Retry.ExecuteRetryAction(() =>
                    {
                        con.Open();
                    }, () =>
                    {
                        con.Close();
                    });
                }
                catch (Exception ex)
                {
                    eventArgs.DisplayColor    = Color.Red;
                    eventArgs.PercentComplete = 100;
                    if (ex is SqlException)
                    {
                        eventArgs.DisplayText = CommonFunc.FormatString(Properties.Resources.ProcessAborting, ((SqlException)ex).Number.ToString(), ex.Message, sql.ToString(), DateTime.Now.ToString(CultureInfo.CurrentCulture)) + Environment.NewLine;
                    }
                    else
                    {
                        eventArgs.DisplayText = CommonFunc.FormatString(Properties.Resources.ProcessAborting, "", ex.Message, sql.ToString(), DateTime.Now.ToString(CultureInfo.CurrentCulture)) + Environment.NewLine;
                    }
                    updateStatus(eventArgs);
                    return;
                }

                lCharCnt = 0;
                foreach (string sqlCmd in cah.Lines)
                {
                    ++sqlCmdLoopCtr;
                    if (CancelProcessing)
                    {
                        con.Close();
                        eventArgs.StatusMsg       = Properties.Resources.Canceled;
                        eventArgs.DisplayColor    = Color.DarkCyan;
                        eventArgs.DisplayText     = Environment.NewLine + CommonFunc.FormatString(Properties.Resources.ProcessCanceledAt, DateTime.Now.ToString(CultureInfo.CurrentCulture)) + Environment.NewLine;
                        eventArgs.PercentComplete = 100;
                        updateStatus(eventArgs);
                        return;
                    }

                    if (inBCPCommand)
                    {
                        if (sqlCmd.Length == 0)
                        {
                            ++lCharCnt;
                            continue;  // Get rid of blank line when in BCP Command
                        }
                        if (sqlCmd.StartsWith(Properties.Resources.Go) && !cah.IsIndexInComments(lCharCnt))
                        {
                            sql.Remove(0, sql.Length);
                            inBCPCommand = false;
                            lCharCnt    += sqlCmd.Length + cah.CrLf;
                            continue;
                        }
                    }

                    if (sqlCmd.StartsWith(CommonFunc.FormatString(Properties.Resources.RemoveComment)))
                    {
                        lCharCnt += sqlCmd.Length + cah.CrLf;
                        continue;  // Get rid of program generated comments
                    }

                    if (!comment)
                    {
                        idx = sqlCmd.IndexOf(CommonFunc.FormatString(Properties.Resources.RemoveCommentStart));
                        if (idx > -1)
                        {
                            comment   = true;
                            lCharCnt += sqlCmd.Length + cah.CrLf;
                            continue;
                        }
                    }
                    else
                    {
                        idx = sqlCmd.IndexOf(CommonFunc.FormatString(Properties.Resources.RemoveCommentEnd));
                        if (idx > -1)
                        {
                            comment   = false;
                            lCharCnt += sqlCmd.Length + cah.CrLf;
                            continue;
                        }
                        lCharCnt += sqlCmd.Length + cah.CrLf;
                        continue;
                    }

                    // Look for BCP string.  I.E. "-- BCPArgs:2345:.dbo.Categories" in "C:\Users\ghuey\AppData\Local\Temp\tmp1CD8.tmp" -n -E
                    if (sqlCmd.StartsWith("-- BCPArgs:", StringComparison.Ordinal))
                    {
                        BCPUploadData(targetServer, updateStatus, queueBCPJob, sqlCmd.Substring(11), ref bcpUploadCommands);

                        // if queueBCPJob is null, then BCP upload is not queued up for a parallel batch process (basically, it is finished by now).
                        if (queueBCPJob == null)
                        {
                            ++AsyncProcessingStatus.NumberOfCommandsExecuted;
                            eventArgs.DisplayText     = "";
                            eventArgs.PercentComplete = (int)(((float)AsyncProcessingStatus.NumberOfCommandsExecuted / (float)AsyncProcessingStatus.NumberOfCommands) * 100.0);
                            eventArgs.StatusMsg       = CommonFunc.FormatString(Properties.Resources.BCPProcessingStatus, AsyncProcessingStatus.NumberOfCommandsExecuted.ToString(), AsyncProcessingStatus.NumberOfCommands.ToString());
                            updateStatus(eventArgs);
                        }
                        inBCPCommand = true;
                        lCharCnt    += sqlCmd.Length + cah.CrLf;
                        continue;
                    }

                    if (sqlCmd.StartsWith(CommonFunc.FormatString(Properties.Resources.Go)) && !cah.IsIndexInComments(lCharCnt) || sqlCmdLoopCtr == cah.Lines.Count())
                    {
                        if (sql.Length == 0)
                        {
                            lCharCnt += sqlCmd.Length + cah.CrLf;
                            continue;
                        }

                        try
                        {
                            Retry.ExecuteRetryAction(() =>
                            {
                                NonQueryResults nqr = SqlHelper.ExecuteNonQuery(con, CommandType.Text, sql.ToString());
                            }, () =>
                            {
                                ResetConnection(con);
                            });

                            Match cmdStr = Regex.Match(sql.ToString(), "(CREATE|ALTER)[\\w\\W]+(INDEX|TABLE|VIEW|PROCEDURE|ROLE|SCHEMA|TRIGGER|TYPE).*", RegexOptions.IgnoreCase);
                            if (cmdStr.Success)
                            {
                                int cr = cmdStr.Value.IndexOf("\r");
                                if (cr > 0)
                                {
                                    currentObject = cmdStr.Value.Substring(0, cr > 70 ? 70 : cr);
                                }
                                else
                                {
                                    currentObject = cmdStr.Value.Substring(0, cmdStr.Value.Length > 70 ? 70 : cmdStr.Value.Length);
                                }
                            }
                            else
                            {
                                currentObject = sql.ToString().Substring(0, sql.ToString().Length > 70 ? 70 : sql.ToString().Length);
                            }
                            currentObject = currentObject.Replace("\r", "").Replace("\n", " ");

                            eventArgs.DisplayColor = Color.DarkGreen;
                            eventArgs.DisplayText  = Properties.Resources.Success + " " + currentObject + Environment.NewLine;
                        }
                        catch (Exception ex)
                        {
                            eventArgs.DisplayColor = Color.Red;
                            if (ex is SqlException)
                            {
                                if (((SqlException)ex).Number == 208)
                                {
                                    --AsyncProcessingStatus.NumberOfCommandsExecuted;
                                    sqlDepends.Add(sql.ToString());
                                    eventArgs.DisplayText = "";
                                }
                                else
                                {
                                    eventArgs.DisplayText = DateTime.Now.ToString(CultureInfo.CurrentCulture) + CommonFunc.FormatString(Properties.Resources.ErrorNumAndMsg, ((SqlException)ex).Number.ToString(), ex.Message) + Environment.NewLine + sql.ToString() + Environment.NewLine;
                                }
                            }
                            else
                            {
                                eventArgs.DisplayText = DateTime.Now.ToString(CultureInfo.CurrentCulture) + CommonFunc.FormatString(Properties.Resources.ErrorNumAndMsg, "", ex.Message) + Environment.NewLine + sql.ToString() + Environment.NewLine;
                            }
                        }

                        ++AsyncProcessingStatus.NumberOfCommandsExecuted;
                        eventArgs.PercentComplete = (int)(((float)AsyncProcessingStatus.NumberOfCommandsExecuted / (float)AsyncProcessingStatus.NumberOfCommands) * 100.0);
                        eventArgs.StatusMsg       = CommonFunc.FormatString(Properties.Resources.BCPProcessingStatus, AsyncProcessingStatus.NumberOfCommandsExecuted.ToString(), AsyncProcessingStatus.NumberOfCommands.ToString());
                        updateStatus(eventArgs);
                        sql.Remove(0, sql.Length);
                    }
                    else
                    {
                        sql.AppendLine(sqlCmd);
                    }
                    lCharCnt += sqlCmd.Length + cah.CrLf;
                }

                // Ok, check for error that happened because of dependency and retry

                foreach (string sqlDep in sqlDepends)
                {
                    try
                    {
                        Retry.ExecuteRetryAction(() =>
                        {
                            NonQueryResults nqr = SqlHelper.ExecuteNonQuery(con, CommandType.Text, sqlDep);
                        },
                                                 () =>
                        {
                            ResetConnection(con);
                        });

                        int startIdx = sqlDep.IndexOf("CREATE ", 0, StringComparison.CurrentCultureIgnoreCase);
                        if (startIdx < 0)
                        {
                            startIdx = sqlDep.IndexOf("ALTER ", 0, StringComparison.CurrentCultureIgnoreCase);
                        }
                        int len = sqlDep.Substring(startIdx).Length > 70 ? 70 : sqlDep.Substring(startIdx).Length;
                        currentObject = sqlDep.Substring(startIdx, len) + " ...";

                        eventArgs.DisplayColor = Color.DarkGreen;
                        eventArgs.DisplayText  = Properties.Resources.Success + " " + currentObject.Replace("\r", "").Replace("\n", " ") + Environment.NewLine;
                    }
                    catch (Exception ex)
                    {
                        eventArgs.DisplayColor = Color.Red;
                        if (ex is SqlException)
                        {
                            eventArgs.DisplayText = DateTime.Now.ToString(CultureInfo.CurrentCulture) + CommonFunc.FormatString(Properties.Resources.ErrorNumAndMsg, ((SqlException)ex).Number.ToString(), ex.Message) + Environment.NewLine + sql.ToString() + Environment.NewLine;
                        }
                        else
                        {
                            eventArgs.DisplayText = DateTime.Now.ToString(CultureInfo.CurrentCulture) + CommonFunc.FormatString(Properties.Resources.ErrorNumAndMsg, "", ex.Message) + Environment.NewLine + sql.ToString() + Environment.NewLine;
                        }
                    }

                    ++AsyncProcessingStatus.NumberOfCommandsExecuted;
                    eventArgs.PercentComplete = (int)(((float)AsyncProcessingStatus.NumberOfCommandsExecuted / (float)AsyncProcessingStatus.NumberOfCommands) * 100.0);
                    eventArgs.StatusMsg       = CommonFunc.FormatString(Properties.Resources.BCPProcessingStatus, AsyncProcessingStatus.NumberOfCommandsExecuted.ToString(), AsyncProcessingStatus.NumberOfCommands.ToString());
                    updateStatus(eventArgs);
                }
                con.Close();

                // Output BCP upload command summary
                if (bcpUploadCommands.Count > 0)
                {
                    eventArgs.DisplayColor    = Color.Green;
                    eventArgs.DisplayText     = Properties.Resources.BCPUploadSummary + Environment.NewLine;
                    eventArgs.PercentComplete = 99;
                    updateStatus(eventArgs);

                    foreach (string bcpUploadCommand in bcpUploadCommands)
                    {
                        eventArgs.DisplayText = bcpUploadCommand + Environment.NewLine;
                        updateStatus(eventArgs);
                    }
                }

                AsyncProcessingStatus.FinishedAddingJobs = true;

                while (true)
                {
                    if (AsyncProcessingStatus.FinishedProcessingJobs)
                    {
                        break;
                    }
                    Thread.Sleep(500);
                }

                // Done

                DateTime dtEnd      = DateTime.Now;
                TimeSpan tsDuration = dtEnd.Subtract(dtStart);
                string   sHour      = tsDuration.Hours == 1 ? Properties.Resources.TimeHour : Properties.Resources.TimeHours;
                string   sMin       = tsDuration.Minutes == 1 ? Properties.Resources.TimeMinute : Properties.Resources.TimeMinutes;
                string   sSecs      = tsDuration.Seconds == 1 ? Properties.Resources.TimeSecond : Properties.Resources.TimeSeconds;

                eventArgs.StatusMsg       = Properties.Resources.Done;
                eventArgs.DisplayColor    = Color.DarkCyan;
                eventArgs.DisplayText     = CommonFunc.FormatString(Properties.Resources.ProcessingFinished, dtEnd.ToString(), dtEnd.ToUniversalTime().ToString(), tsDuration.Hours + sHour + tsDuration.Minutes.ToString() + sMin + tsDuration.Seconds.ToString() + sSecs);
                eventArgs.PercentComplete = 100;
                updateStatus(eventArgs);
            }
        }
Esempio n. 57
0
 public static void Add_ExplicitInterface_Test(StringCollection collection, string[] data)
 {
     IList added = new StringCollection();
     for (int i = 0; i < data.Length; i++)
     {
         Assert.Equal(i, added.Count);
         Assert.Throws<ArgumentOutOfRangeException>(() => added[i]);
         added.Add(data[i]);
         Assert.Equal(data[i], added[i]);
         Assert.Equal(i + 1, added.Count);
     }
     Assert.Equal(collection, added);
 }
        // 創建新Favorite
        private void Favorite_Create_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.Current_Favorite = Favorite_Name.Text;
            if (Favorite_Name.Text == string.Empty)
            {
                MessageBox.Show("Please Enter Favorite Name");
                return;
            }
            else
            {
                if (Properties.Settings.Default.Favorite_List == null)
                {
                    // 存名稱
                    StringCollection favorite_list = new StringCollection();
                    favorite_list.Add(Favorite_Name.Text); // 加入新資料

                    // 存路徑
                    Dictionary <string, string> favorite_path = new Dictionary <string, string>();
                    favorite_path.Add(Favorite_Name.Text, GloableObject.curPath);
                    string           jsonStr            = JsonConvert.SerializeObject(favorite_path, Formatting.Indented);
                    StringCollection favorite_path_list = new StringCollection();
                    favorite_path_list.Add(jsonStr); // 加入新資料

                    // 存控件
                    Dictionary <string, Dictionary <string, List <string> > > favorite_controls = new Dictionary <string, Dictionary <string, List <string> > >();
                    Dictionary <string, List <string> > controls_list = new Dictionary <string, List <string> >();

                    int controls_counter = 0;
                    foreach (Folder_Control control in GloableObject.mainWin.control_panel.Children)
                    {
                        string        control_num  = "control_" + controls_counter.ToString();
                        List <string> control_data = new List <string>();

                        //顏色
                        string color = control.colorTag.Background.ToString();
                        control_data.Add(color);
                        //aka
                        string aka = control.akaLabel.Text;
                        control_data.Add(aka);
                        //path
                        string path = control.folderPath.Text;
                        control_data.Add(path);

                        controls_list.Add(control_num, control_data); //{"control_x":"[color, aka, path]"}

                        controls_counter += 1;
                    }
                    favorite_controls.Add(Favorite_Name.Text, controls_list); //{"favor_name":{"control_x":"[color, aka, path]}}
                    string           controls_jsonStr       = JsonConvert.SerializeObject(favorite_controls, Formatting.Indented);
                    StringCollection favorite_controls_list = new StringCollection();
                    favorite_controls_list.Add(controls_jsonStr);

                    // 存檔
                    Properties.Settings.Default.Favorite_List          = favorite_list;
                    Properties.Settings.Default.Favorite_Path_List     = favorite_path_list;
                    Properties.Settings.Default.Favorite_Controls_List = favorite_controls_list;
                    Properties.Settings.Default.Save();
                }
                else
                {
                    // 存名稱
                    StringCollection favorite_list = new StringCollection();
                    // 加回已存在的資料
                    foreach (string favorite in Properties.Settings.Default.Favorite_List)
                    {
                        favorite_list.Add(favorite);
                    }
                    favorite_list.Add(Favorite_Name.Text); // 加入新資料

                    // 存路徑
                    Dictionary <string, string> favorite_path = new Dictionary <string, string>();
                    favorite_path.Add(Favorite_Name.Text, GloableObject.curPath); //{"name":"path"}
                    string path_jsonStr = JsonConvert.SerializeObject(favorite_path, Formatting.Indented);

                    StringCollection favorite_path_list = new StringCollection();
                    // 加回已存在的資料
                    if (Properties.Settings.Default.Favorite_Path_List != null)
                    {
                        foreach (string path in Properties.Settings.Default.Favorite_Path_List)
                        {
                            favorite_path_list.Add(path);
                        }
                    }
                    favorite_path_list.Add(path_jsonStr); // 加入新資料

                    // 存控件
                    Dictionary <string, Dictionary <string, List <string> > > favorite_controls = new Dictionary <string, Dictionary <string, List <string> > >();
                    Dictionary <string, List <string> > controls_list = new Dictionary <string, List <string> >();
                    // 加回已存在的資料
                    StringCollection favorite_controls_list = new StringCollection();
                    foreach (string name in Properties.Settings.Default.Favorite_Controls_List)
                    {
                        favorite_controls_list.Add(name);
                    }

                    int controls_counter = 0;
                    foreach (Folder_Control control in GloableObject.mainWin.control_panel.Children)
                    {
                        string        control_num  = "control_" + controls_counter.ToString();
                        List <string> control_data = new List <string>();

                        //顏色
                        string color = control.colorTag.Background.ToString();
                        control_data.Add(color);
                        //aka
                        string aka = control.akaLabel.Text;
                        control_data.Add(aka);
                        //path
                        string path = control.folderPath.Text;
                        control_data.Add(path);

                        controls_list.Add(control_num, control_data); //{"control_x":"[color, aka, path]"}

                        controls_counter += 1;
                    }
                    favorite_controls.Add(Favorite_Name.Text, controls_list); //{"favor_name":{"control_x":"[color, aka, path]}}
                    string controls_jsonStr = JsonConvert.SerializeObject(favorite_controls, Formatting.Indented);
                    favorite_controls_list.Add(controls_jsonStr);

                    Properties.Settings.Default.Favorite_List          = favorite_list;
                    Properties.Settings.Default.Favorite_Path_List     = favorite_path_list;
                    Properties.Settings.Default.Favorite_Controls_List = favorite_controls_list;
                    Properties.Settings.Default.Save();
                }
                Window.GetWindow(this).Close();
                GloableObject.logger($"✔🤍 [Create Favorite] - Create Favorite {Favorite_Name.Text}.", "HighLight");
            }
        }
Esempio n. 59
0
 public static void GetEnumerator_ModifiedCollectionTest(StringCollection collection, string[] data)
 {
     StringEnumerator enumerator = collection.GetEnumerator();
     Assert.NotNull(enumerator);
     if (data.Length > 0)
     {
         Assert.True(enumerator.MoveNext());
         string current = enumerator.Current;
         Assert.Equal(data[0], current);
         collection.RemoveAt(0);
         if (data.Length > 1 && data[0] != data[1])
         {
             Assert.NotEqual(current, collection[0]);
         }
         Assert.Equal(current, enumerator.Current);
         Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
         Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
     }
     else
     {
         collection.Add("newValue");
         Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
     }
 }
Esempio n. 60
0
        /// <summary>
        /// write the interfaces for the methods that need to be reflected
        /// check connector files
        /// </summary>
        /// <param name="ATemplate"></param>
        /// <param name="AMethodsAlreadyWritten">write methods only once</param>
        /// <param name="AConnectorClasses">the classes that are implementing the methods</param>
        /// <param name="AInterfaceName">the interface that is written at the moment</param>
        /// <param name="AInterfaceNamespace">only needed to shorten the type names to improve readability</param>
        /// <param name="AServerNamespace">for the comment in the autogenerated code</param>
        /// <returns></returns>
        private bool WriteConnectorMethods(
            ProcessTemplate ATemplate,
            ref StringCollection AMethodsAlreadyWritten,
            List <TypeDeclaration> AConnectorClasses, String AInterfaceName, String AInterfaceNamespace, String AServerNamespace)
        {
            foreach (TypeDeclaration t in AConnectorClasses)
            {
                string ConnectorClassName = t.Name;

                foreach (PropertyDeclaration p in CSParser.GetProperties(t))
                {
                    if (TCollectConnectorInterfaces.IgnoreMethod(p.Attributes, p.Modifier))
                    {
                        continue;
                    }

                    // don't write namespace hierarchy here
                    if (p.TypeReference.Type.IndexOf("Namespace") == -1)
                    {
                        String returnType = AutoGenerationTools.TypeToString(p.TypeReference, AInterfaceNamespace);

                        // this interface got implemented somewhere on the server
                        ProcessTemplate snippet = ATemplate.GetSnippet("CONNECTORPROPERTY");
                        snippet.SetCodelet("CONNECTORCLASSNAME", ConnectorClassName);
                        snippet.SetCodelet("SERVERNAMESPACE", AServerNamespace);
                        snippet.SetCodelet("TYPE", returnType);
                        snippet.SetCodelet("NAME", p.Name);

                        if (p.HasGetRegion)
                        {
                            snippet.SetCodelet("GETTER", "true");
                        }

                        if (p.HasSetRegion)
                        {
                            snippet.SetCodelet("SETTER", "true");
                        }

                        ATemplate.InsertSnippet("CONTENT", snippet);
                    }
                }

                foreach (MethodDeclaration m in CSParser.GetMethods(t))
                {
                    string MethodName = m.Name;

                    if (TCollectConnectorInterfaces.IgnoreMethod(m.Attributes, m.Modifier))
                    {
                        continue;
                    }

                    String formattedMethod = "";
                    String returnType      = AutoGenerationTools.TypeToString(m.TypeReference, AInterfaceNamespace);

                    int align = (returnType + " " + m.Name).Length + 1;

                    // this interface got implemented somewhere on the server
                    formattedMethod = "/// <summary> auto generated from Connector method(" + AServerNamespace + "." + ConnectorClassName +
                                      ")</summary>" + Environment.NewLine;
                    formattedMethod += returnType + " " + m.Name + "(";

                    bool firstParameter = true;

                    foreach (ParameterDeclarationExpression p in m.Parameters)
                    {
                        if (!firstParameter)
                        {
                            ATemplate.AddToCodelet("CONTENT", formattedMethod + "," + Environment.NewLine);
                            formattedMethod = new String(' ', align);
                        }

                        firstParameter = false;
                        String parameterType = AutoGenerationTools.TypeToString(p.TypeReference, "");

                        if ((p.ParamModifier & ParameterModifiers.Ref) != 0)
                        {
                            formattedMethod += "ref ";
                        }
                        else if ((p.ParamModifier & ParameterModifiers.Out) != 0)
                        {
                            formattedMethod += "out ";
                        }

                        formattedMethod += parameterType + " " + p.ParameterName;
                    }

                    formattedMethod += ");";
                    AMethodsAlreadyWritten.Add(MethodName);
                    ATemplate.AddToCodelet("CONTENT", formattedMethod + Environment.NewLine);
                }
            }

            return(true);
        }