Beispiel #1
0
    private void BindData()
    {
        string SessionIDName = "CAM051_" + PageTimeStamp.Value;
        MaintainStoreTransfer bco = new MaintainStoreTransfer(ConntionDB);

        DataTable dt = bco.QueryStoreTransfer(chkLike.Checked, txtGroup.Text, txtStore.Text,
                            txtProfit.Text, txtZO.Text, txtSalID.Text, txtAcctUID.Text,
                            ddlIOType.SelectedValue, txtTransferDate.StartDate, txtTransferDate.EndDate,
                            txtBusDate.StartDate, txtBusDate.EndDate, txtTransferNo.Text,
                            txtChainSourceNo.Text, txtInAcctNo.Text, rblTaxType.Text,
                            txtRootNo.Text, rblIsSchedule.SelectedValue, ddlACStatus.Text,
                            txtACBalanceDateS.Text, txtACBalanceDate.Text, txtItem.Text,
                            txtPeriod.Text, txtAdjQty.Text, txtAdjQty.Operator, TextBoxRowCountLimit.Text, SLP_CreateUID.Text, SLP_UpdateUID.Text,
                            slpPROMOTE_ID_S.Text, slpPROMOTE_ID_E.Text);

        Session[SessionIDName] = dt;
        GridView1.DataSource = dt;
        GridView1.PageSize = (TextBoxPagesize.Text == "") ? 10 : (int.Parse(TextBoxPagesize.Text) < 0) ? 10 : int.Parse(TextBoxPagesize.Text);
        GridView1.PageIndex = 0;
        GridView1.DataBind();

        if (dt.Rows.Count > 0)
        {
            StringCollection sc = new StringCollection();
            foreach (DataRow dr in dt.Rows)
            {
                sc.Add(dr["ID"].ToString());
            }
            Session["CAM05CodeCollection"] = sc;
        }
        else
        {
            ErrorMsgLabel.Text = "查無資料";
        }
    }
    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");
        }
    }
Beispiel #3
0
Datei: test.cs Projekt: 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));
	}
		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);

		}
        //string wth; FIXED -- Issue with object scope? Will fix later. This is a workaround.
        public MainForm()
        {
            InitializeComponent();
            buttonUpload.Enabled = false; //Disable buttons by default.
            textComplete.Visible = false;
            btnDelete.Enabled = false;
            btnAdd.Enabled = false;

            comboCategory.SelectedIndex = 7; //No selection is invalid.
            vidFlag = false;            //User must provide credentials and a video before uploading.
            loginFlag = false;

            //Saved settings
            folderBrowserDialog.SelectedPath = stored_IncludeFolder;
            includeTextBox.Text = stored_IncludeFolder;
            VideoWatcher.Path = stored_IncludeFolder;

            VideoFilename = Youtube_Uploader.Properties.Settings.Default.FilesLib;
            VideoId = Youtube_Uploader.Properties.Settings.Default.IdLib;
            VideoStatus = Youtube_Uploader.Properties.Settings.Default.StatusLib;

            YouTubeRequestSettings settings = new YouTubeRequestSettings("Deprecated", key, Youtube_Uploader.Properties.Settings.Default.UsernameYT, Youtube_Uploader.Properties.Settings.Default.PasswordYT);
            request = new YouTubeRequest(settings);

            drawVideoList();
        }
Beispiel #6
0
	public static void Say(this ChatClient chat, string to, StringCollection lines)
	{
		foreach (string line in lines)
		{
			chat.Say(to, line);
		}
	}
		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);
        }
Beispiel #9
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;
    }
		/// <summary>
		/// This call is used to verify that the data you plan to pass into a <b>RelistItem</b> call will produce the results that you are expecting, including a successful call with no errors.
		/// </summary>
		/// 
		/// <param name="Item">
		/// Child elements hold the values for item properties that change for the
		/// relisted item. Item is a required input. At a minimum, the Item.ItemID
		/// property must be set to the ID of the listing being relisted (a
		/// listing that ended in the past 90 days). By default, the new listing's
		/// Item object properties are the same as those of the original (ended)
		/// listing. By setting a new value in the Item object, the new listing
		/// uses the new value rather than the corresponding value from the old
		/// listing.
		/// </param>
		///
		/// <param name="DeletedFieldList">
		/// Specifies the name of the field to delete from a listing. See the eBay Features Guide for rules on deleting values when relisting items. Also see the relevant field descriptions to determine when to use <b>DeletedField</b> (and potential consequences).
		/// The request can contain zero, one, or many instances of <b>DeletedField</b> (one for each field to be deleted).
		/// 
		/// Case-sensitivity must be taken into account when using a <b>DeletedField</b> tag to delete a field. The value passed into a <b>DeletedField</b> tag must either match the case of the schema element names in the full field path (Item.PictureDetails.GalleryURL), or the initial letter of each schema element name in the full field path must be  lowercase (item.pictureDetails.galleryURL).
		/// Do not change the case of letters in the middle of a field name.
		/// For example, item.picturedetails.galleryUrl is not allowed.
		/// To delete a listing enhancement like 'BoldTitle', specify the value you are deleting;
		/// for example, Item.ListingEnhancement[BoldTitle].
		/// </param>
		///
		public string VerifyRelistItem(ItemType Item, StringCollection DeletedFieldList)
		{
			this.Item = Item;
			this.DeletedFieldList = DeletedFieldList;

			Execute();
			return ApiResponse.ItemID;
		}
Beispiel #11
0
Datei: test.cs Projekt: mono/gert
		public AssemblyResolveHandler (StringCollection probePaths)
		{
			_probePaths = probePaths;

			// attach handlers for the current domain.
			AppDomain.CurrentDomain.AssemblyResolve +=
				new ResolveEventHandler (ResolveAssembly);
		}
		/// <summary>
		/// Enables Selling Manager subscribers to store standard feedback comments that can
		/// be left for their buyers. Selling Manager Pro subscribers can also specify what
		/// events, if any, will trigger an automated feedback to buyers.
		/// </summary>
		/// 
		/// <param name="AutomatedLeaveFeedbackEvent">
		/// Specifies the event that will trigger automated feedback to the buyer.
		/// Applies to Selling Manager Pro subscribers only.
		/// </param>
		///
		/// <param name="StoredCommentList">
		/// Contains a set of comments from which one can be selected to leave
		/// feedback for a buyer. If automated feedback is used, a comment is
		/// selected from the set randomly. Automated feedback applies to Selling
		/// Manager Pro subscribers only. Stored comments cannot be replaced or
		/// edited individually. Submitting a stored comments array replaces all
		/// existing stored comments.
		/// 
		/// </param>
		///
		public void SetSellingManagerFeedbackOptions(AutomatedLeaveFeedbackEventCodeType AutomatedLeaveFeedbackEvent, StringCollection StoredCommentList)
		{
			this.AutomatedLeaveFeedbackEvent = AutomatedLeaveFeedbackEvent;
			this.StoredCommentList = StoredCommentList;

			Execute();
			
		}
		/// <summary>
		/// Enables a seller to relist a single listing that has ended on a specified eBay site.
		/// </summary>
		/// 
		/// <param name="Item">
		/// Child elements hold the values for item properties that change for the
		/// relisted item. Item is a required input. At a minimum, the Item.ItemID
		/// property must be set to the ID of the listing being relisted (a
		/// listing that ended in the past 90 days). By default, the new listing's
		/// Item object properties are the same as those of the original (ended)
		/// listing. By setting a new value in the Item object, the new listing
		/// uses the new value rather than the corresponding value from the old
		/// listing.
		/// </param>
		///
		/// <param name="DeletedFieldList">
		/// Specifies the name of the field to delete from a listing.
		/// See the eBay Features Guide for rules on deleting values when relisting items.
		/// Also see the relevant field descriptions to determine when to use <b>DeletedField</b> (and potential consequences).
		/// The request can contain zero, one, or many instances of <b>DeletedField</b> (one for each field to be deleted).
		/// 
		/// Case-sensitivity must be taken into account when using a <b>DeletedField</b> tag to delete a field. The value passed into a <b>DeletedField</b> tag must either match the case of the schema element names in the full field path (Item.PictureDetails.GalleryURL), or the initial letter of each schema element name in the full field path must be  lowercase (item.pictureDetails.galleryURL).
		/// Do not change the case of letters in the middle of a field name.
		/// For example, item.picturedetails.galleryUrl is not allowed.
		/// To delete a listing enhancement like 'BoldTitle', specify the value you are deleting;
		/// for example, Item.ListingEnhancement[BoldTitle].
		/// </param>
		///
		public FeeTypeCollection RelistItem(ItemType Item, StringCollection DeletedFieldList)
		{
			this.Item = Item;
			this.DeletedFieldList = DeletedFieldList;

			Execute();
			return ApiResponse.Fees;
		}
		/// <summary>
		/// Removes selected messages for a given user.
		/// </summary>
		/// 
		/// <param name="AlertIDList">
		/// This field will be deprecated in an upcoming release. This field formerly
		/// contained a list of up to 10 AlertID values.
		/// </param>
		///
		/// <param name="MessageIDList">
		/// Contains a list of up to 10 MessageID values.
		/// </param>
		///
		public void DeleteMyMessages(StringCollection AlertIDList, StringCollection MessageIDList)
		{
			this.AlertIDList = AlertIDList;
			this.MessageIDList = MessageIDList;

			Execute();
			
		}
Beispiel #15
0
		public ApeItem()
		{
			type = ApeItemType.Text;
			//key = null;
			//value = null;
			text = new StringCollection();
			//readOnly = false;
		}
 private static void GetAllAssembly(Assembly assembly, StringCollection stringCollection)
 {
     string location = assembly.Location;
     if (!stringCollection.Contains(location))
     {
         stringCollection.Add(location);
     }
 }
		/// <summary>
		/// This call is use to add one or more order line items to an eBay user's My eBay Watch List. An auction item or a single-variation, fixed-price listing is identified with an <b>ItemID</b> value. To add a specific item variation to the Watch List from within a multi-variation, fixed-price listing, the user will use the  <b>VariationKey</b> container
		/// </summary>
		/// 
		/// <param name="ItemIDList">
		/// The <b>ItemID</b> of the item that is to be added to the eBay user's Watch List.
		/// The item must be a currently active item, and the total number
		/// of items in the user's
		/// Watch List (after the items in the request have been added) cannot exceed
		/// the maximum allowed number of Watch List items. One or more <b>ItemID</b> fields can be specified. A separate error node will be
		/// returned for each item that fails.
		/// 
		/// Either <b>ItemID</b> or <b>VariationKey</b> is required
		/// (but do not pass in both).
		/// </param>
		///
		/// <param name="VariationKeyList">
		/// A variation (or set of variations) that you want to add to the Watch List.
		/// Use this to watch a particular variation (not the entire item).
		/// Either the top-level <b>ItemID</b> or <b>VariationKey</b> is required
		/// (but do not pass in both).
		/// </param>
		///
		public int AddToWatchList(StringCollection ItemIDList, VariationKeyTypeCollection VariationKeyList)
		{
			this.ItemIDList = ItemIDList;
			this.VariationKeyList = VariationKeyList;

			Execute();
			return ApiResponse.WatchListCount;
		}
		/// <summary>
		/// Gives approved sellers the ability to extend the default and
		/// ongoing lifetime of pictures uploaded to eBay.
		/// </summary>
		/// 
		/// <param name="PictureURLList">
		/// The URL of the image hosted by eBay Picture Services.
		/// </param>
		///
		/// <param name="ExtensionInDays">
		/// The number of days by which to extend the expiration date for the
		/// specified image.
		/// </param>
		///
		public StringCollection ExtendSiteHostedPictures(StringCollection PictureURLList, int ExtensionInDays)
		{
			this.PictureURLList = PictureURLList;
			this.ExtensionInDays = ExtensionInDays;

			Execute();
			return ApiResponse.PictureURL;
		}
Beispiel #19
0
 protected void Dump(StringCollection strings)
 {
     foreach (String s in strings)
     {
         Console.Out.Write(String.Format("{0}, ", s));
     }
     Console.Out.WriteLine();
 }
Beispiel #20
0
 /// <summary>
 /// Default constructor
 /// </summary>
 private Erf()
 {
     removedFiles = new StringCollection();
     keyHash = new Hashtable(5000);
     addedFileHash = new Hashtable(1000);
     replacedFileHash = new Hashtable(1000);
     decompressedPath = string.Empty;
 }
 private static StringCollection BuildList()
 {
     StringCollection list = new StringCollection();
     list.Add("ABC");
     list.Add("DEF");
     list.Add("GHI");
     return list;
 }
Beispiel #22
0
Datei: test.cs Projekt: 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;
	}
		/// <summary>
		/// Enables a user to remove one or more items from their My eBay watch list.
		/// </summary>
		/// 
		/// <param name="ItemIDList">
		/// The ID of the item to be removed from the
		/// watch list. Either ItemID, RemoveAllItems, or VariationKey must
		/// be specified, but NOT more than one of these.
		/// Multiple ItemID fields can be specified in the same request.
		/// </param>
		///
		/// <param name="RemoveAllItems">
		/// If true, then all the items in the user's
		/// watch list are removed. Either ItemID, RemoveAllItems, or VariationKey must be specified, but NOT more than one of these.
		/// </param>
		///
		/// <param name="VariationKeyList">
		/// A variation (or set of variations) that you want to remove
		/// from the watch list. Either ItemID, RemoveAllItems, or VariationKey must be specified, but NOT more than one of these.
		/// </param>
		///
		public int RemoveFromWatchList(StringCollection ItemIDList, bool RemoveAllItems, VariationKeyTypeCollection VariationKeyList)
		{
			this.ItemIDList = ItemIDList;
			this.RemoveAllItems = RemoveAllItems;
			this.VariationKeyList = VariationKeyList;

			Execute();
			return ApiResponse.WatchListCount;
		}
		/// <summary>
		/// Renames, removes, or restores the specified My Messages folders for
		/// a given user.
		/// </summary>
		/// 
		/// <param name="Operation">
		/// Indicates the type of operation to perform on a
		/// specified My Messages folder. Operations include creating,
		/// renaming, removing, and restoring folders. Operations
		/// cannot be performed on the Inbox and Sent folders.
		/// </param>
		///
		/// <param name="FolderIDList">
		/// An ID that uniquely identifies the My Messages
		/// folder to perform the operation on. This value is set by
		/// eBay and cannot be changed. Retrieve FolderIDs
		/// by calling GetMyMessages with a DetailLevel of
		/// ReturnSummary. Inbox is FolderID = 0, and Sent is
		/// FolderID = 1.
		/// </param>
		///
		/// <param name="FolderNameList">
		/// The name of a specified My Messages folder. Depending
		/// on the specified Operation, the value is an existing
		/// folder name or a new folder name. Retrieve existing
		/// FolderNames by calling GetMyMessages with a DetailLevel
		/// of ReturnSummary. Inbox is FolderID = 0, and Sent is
		/// FolderID = 1.
		/// </param>
		///
		public void ReviseMyMessagesFolders(MyMessagesFolderOperationCodeType Operation, Int64Collection FolderIDList, StringCollection FolderNameList)
		{
			this.Operation = Operation;
			this.FolderIDList = FolderIDList;
			this.FolderNameList = FolderNameList;

			Execute();
			
		}
 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;
 }
		/// <summary>
		/// Retrieves top-ranked contextual eBay keywords and categories
		/// for a specified web page.
		/// </summary>
		/// 
		/// <param name="URL">
		/// The URL of the web page from which eBay is to extract keywords.
		/// </param>
		///
		/// <param name="Encoding">
		/// Web page encoding by which the URL is to be handled, such as ISO-8859-1.
		/// </param>
		///
		/// <param name="CategoryIDList">
		/// The ID of the category to which keywords are to be limited.
		/// Zero or more category IDs can be specified.
		/// </param>
		///
		public ContextSearchAssetTypeCollection GetContextualKeywords(string URL, string Encoding, StringCollection CategoryIDList)
		{
			this.URL = URL;
			this.Encoding = Encoding;
			this.CategoryIDList = CategoryIDList;

			Execute();
			return ApiResponse.ContextSearchAsset;
		}
Beispiel #27
0
        public void relistItems()
        {
            MySQLWrapper s = null;

            try
            {
                changeStatus("Initializing...");
                addLogStatus("Initializing...");
                if (!initialize())
                    throw new Exception("ERROR : Unable to connect to eBay Service");
                s = new MySQLWrapper();
                GetMyeBaySellingCall eBaySelling = new GetMyeBaySellingCall(context);
                PaginatedItemArrayType pArr = new PaginatedItemArrayType();
                eBaySelling.UnsoldList = new ItemListCustomizationType();
                eBaySelling.UnsoldList.Include = true;
                eBaySelling.GetMyeBaySelling();
                ItemTypeCollection unsoldItems = new ItemTypeCollection();
                pArr = eBaySelling.UnsoldListReturn;
                if (pArr != null)
                {
                    string sku = "";
                    unsoldItems = pArr.ItemArray;
                    RelistItemCall relistItem = new RelistItemCall(context);
                    StringCollection deleteFieldList = new StringCollection();
                    ItemType tItem = new ItemType();
                    changeStatus("ReListing...");
                    addLogStatus("Total Unsold items : " + unsoldItems.Count);
                    for (int i = 0; i < unsoldItems.Count; i++)
                    {
                        tItem.ItemID = unsoldItems[i].ItemID;
                        sku = s.getSKU(unsoldItems[i].ItemID);
                        if(sku != ""){
                            relistItem.RelistItem(tItem);
                            s.updateReListedItem(sku, relistItem.ItemID);
                            s.addToLogs(sku, "Re-Listed with Item Id : " + relistItem.ItemID);
                            addLogStatus("Item : " + unsoldItems[i].ItemID + " relisted with Item ID : " + relistItem.ItemID);
                        }
                        else{
                            throw new Exception("ItemId : " + unsoldItems[i].ItemID + " not found in database!");
                        }
                    }
                    addLogStatus("Done!");
                }
                else {
                    addLogStatus("No Unsold Items!");
                }
            }
            catch (Exception ex)
            {
                addLogStatus("ERROR : " + ex.Message);
            }
            finally {
                s.destroy();
                destroy();
            }
        }
 public void SetSellingManagerFeedbackOptions()
 {
     SetSellingManagerFeedbackOptionsCall api = new SetSellingManagerFeedbackOptionsCall(apiContext);
     api.AutomatedLeaveFeedbackEvent=AutomatedLeaveFeedbackEventCodeType.PaymentReceived;
     StringCollection storedComments =new StringCollection(new string[]{"Paid quickly! Thank you for choosing to buy from Sales-a-lot. "});
     api.StoredCommentList=storedComments;
     api.Execute();
     //check whether the call is success.
     Assert.IsTrue(api.ApiResponse.Ack==AckCodeType.Success || api.ApiResponse.Ack==AckCodeType.Warning,"do not success!");
 }
		/// <summary>
		/// Revises a Selling Manager product.
		/// 
		/// This call is subject to change without notice; the
		/// deprecation process is inapplicable to this call.
		/// </summary>
		/// 
		/// <param name="SellingManagerProductDetails">
		/// The details of the product that is being revised.
		/// </param>
		///
		/// <param name="SellingManagerFolderDetails">
		/// The details of the folder for this product.
		/// </param>
		///
		/// <param name="DeletedFieldList">
		/// Specifies the name of a field to remove from a Selling Manager product.
		/// The request can contain zero, one, or many instances of DeletedField (one for each field to be removed).
		/// DeletedField accepts the following path names, which remove the corresponding fields:
		/// SellingManagerProductDetails.CustomLabel
		/// SellingManagerProductDetails.QuantityAvailable
		/// SellingManagerProductDetails.UnitCost
		/// These values are case-sensitive. Use values that match the case of the schema element names.
		/// </param>
		///
		/// <param name="SellingManagerProductSpecifics">
		/// Specifies an eBay category associated with the product,
		/// defines Item Specifics that are relevant to the product,
		/// and defines variations available for the product
		/// (which may be used to create mult-variation listings).
		/// </param>
		///
		public SellingManagerProductDetailsType ReviseSellingManagerProduct(SellingManagerProductDetailsType SellingManagerProductDetails, SellingManagerFolderDetailsType SellingManagerFolderDetails, StringCollection DeletedFieldList, SellingManagerProductSpecificsType SellingManagerProductSpecifics)
		{
			this.SellingManagerProductDetails = SellingManagerProductDetails;
			this.SellingManagerFolderDetails = SellingManagerFolderDetails;
			this.DeletedFieldList = DeletedFieldList;
			this.SellingManagerProductSpecifics = SellingManagerProductSpecifics;

			Execute();
			return ApiResponse.SellingManagerProductDetails;
		}
        public HttpResponseMessage UpdateTickets(StringCollection ticketIds, string userId, string mode)
        {
            if (ticketIds != null)
            {
                this.ticketService.UpdateTickets(ticketIds, Convert.ToInt32(userId, CultureInfo.CurrentCulture), mode);
                return Request.CreateResponse(HttpStatusCode.OK);
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
Beispiel #31
0
        //
        // ProcessListSetPerMachine() helper lists counter sets on a machine.
        // NOTE: machine argument should be NULL for the local machine
        //
        private void ProcessListSetPerMachine(string machine)
        {
            StringCollection counterSets = new StringCollection();
            uint             res         = _pdhHelper.EnumObjects(machine, ref counterSets);

            if (res != 0)
            {
                //add an error message
                string    msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoCounterSetsOnComputer"), machine, res);
                Exception exc = new Exception(msg);
                WriteError(new ErrorRecord(exc, "NoCounterSetsOnComputer", ErrorCategory.InvalidResult, machine));
                return;
            }

            CultureInfo culture = GetCurrentCulture();
            List <Tuple <char, char> > characterReplacementList = null;
            StringCollection           validPaths = new StringCollection();

            _cultureAndSpecialCharacterMap.TryGetValue(culture.Name, out characterReplacementList);

            foreach (string pattern in _listSet)
            {
                bool   bMatched          = false;
                string normalizedPattern = pattern;

                if (characterReplacementList != null)
                {
                    foreach (Tuple <char, char> pair in characterReplacementList)
                    {
                        normalizedPattern = normalizedPattern.Replace(pair.Item1, pair.Item2);
                    }
                }

                WildcardPattern wildLogPattern = new WildcardPattern(normalizedPattern, WildcardOptions.IgnoreCase);

                foreach (string counterSet in counterSets)
                {
                    if (!wildLogPattern.IsMatch(counterSet))
                    {
                        continue;
                    }

                    StringCollection counterSetCounters  = new StringCollection();
                    StringCollection counterSetInstances = new StringCollection();

                    res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances);
                    if (res == PdhResults.PDH_ACCESS_DENIED)
                    {
                        string    msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSetEnumAccessDenied"), counterSet);
                        Exception exc = new Exception(msg);
                        WriteError(new ErrorRecord(exc, "CounterSetEnumAccessDenied", ErrorCategory.InvalidResult, null));
                        continue;
                    }
                    else if (res != 0)
                    {
                        ReportPdhError(res, false);
                        continue;
                    }

                    string[] instanceArray = new string[counterSetInstances.Count];
                    int      i             = 0;
                    foreach (string instance in counterSetInstances)
                    {
                        instanceArray[i++] = instance;
                    }

                    //
                    // Special case: no instances present: change to * to create a valid paths
                    //
                    if (instanceArray.Length == 1 &&
                        instanceArray[0].Length == 0)
                    {
                        instanceArray[0] = "*";
                    }

                    Dictionary <string, string[]> counterInstanceMapping = new Dictionary <string, string[]>();
                    foreach (string counter in counterSetCounters)
                    {
                        if (!counterInstanceMapping.ContainsKey(counter))
                        {
                            counterInstanceMapping.Add(counter, instanceArray);
                        }
                    }

                    PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
                    if (counterSetInstances.Count > 1)
                    {
                        categoryType = PerformanceCounterCategoryType.MultiInstance;
                    }
                    else //if (counterSetInstances.Count == 1) //???
                    {
                        categoryType = PerformanceCounterCategoryType.SingleInstance;
                    }

                    string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet);

                    CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping);
                    WriteObject(setObj);
                    bMatched = true;
                }

                if (!bMatched)
                {
                    string    msg = _resourceMgr.GetString("NoMatchingCounterSetsFound");
                    Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg,
                                                                machine ?? "localhost", normalizedPattern));
                    WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsFound", ErrorCategory.ObjectNotFound, null));
                }
            }
        }
Beispiel #32
0
        /// <summary>
        /// convert shortname from Lastname, firstname, title to another shortname format
        /// TODO: use partner key to get to the full name, resolve issues with couples that have different family names etc
        /// </summary>
        public static string FormatShortName(string AShortname, eShortNameFormat AFormat)
        {
            if (AShortname.Length == 0)
            {
                return("");
            }

            StringCollection names = StringHelper.StrSplit(AShortname, ",");

            string resultValue = "";

            if (AFormat == eShortNameFormat.eShortname)
            {
                return(AShortname);
            }
            else if (AFormat == eShortNameFormat.eReverseShortname)
            {
                foreach (string name in names)
                {
                    if (resultValue.Length > 0)
                    {
                        resultValue = " " + resultValue;
                    }

                    resultValue = name + resultValue;
                }

                return(resultValue);
            }
            else if (AFormat == eShortNameFormat.eOnlyTitle)
            {
                // organisations&churches have no title, therefore we need to check if there are more than 2 names
                if (names.Count > 2)
                {
                    return(names[names.Count - 1]);
                }

                // eg. Mustermann, Family
                if (names.Count > 1)
                {
                    return(names[1]);
                }
            }
            else if (AFormat == eShortNameFormat.eOnlySurname)
            {
                return(names[0]);
            }
            else if (AFormat == eShortNameFormat.eOnlyFirstname)
            {
                if (names.Count > 1)
                {
                    return(names[1]);
                }
            }
            else if (AFormat == eShortNameFormat.eOnlySurnameFirstNameInitial)
            {
                if (names.Count > 2)
                {
                    // remove the title
                    names.RemoveAt(names.Count - 1);
                }

                if (names.Count > 1)
                {
                    return(names[0] + ", " + names[1].Substring(0, 1) + ".");
                }

                return(names[0]);
            }
            else if (AFormat == eShortNameFormat.eReverseWithoutTitle)
            {
                if (names.Count > 1)
                {
                    // remove the title
                    names.RemoveAt(names.Count - 1);
                }

                foreach (string name in names)
                {
                    if (resultValue.Length > 0)
                    {
                        resultValue = " " + resultValue;
                    }

                    resultValue = name + resultValue;
                }

                return(resultValue);
            }
            else if (AFormat == eShortNameFormat.eReverseLastnameInitialsOnly)
            {
                if (names.Count > 1)
                {
                    // remove the title
                    names.RemoveAt(names.Count - 1);
                }

                if (names.Count > 1)
                {
                    return(names[1] + " " + names[0].Substring(0, 1) + ".");
                }

                return(names[0].Substring(0, 1) + ".");
            }
            else if (AFormat == eShortNameFormat.eJustRemoveTitle)
            {
                if (names.Count > 1)
                {
                    // remove the title
                    names.RemoveAt(names.Count - 1);
                }

                if (names.Count > 1)
                {
                    return(names[0] + ", " + names[1]);
                }

                return(names[0]);
            }

            return("");
        }
 ///<summary>
 /// Объединяет коллекцию строк в одну строку использую разделитель
 ///</summary>
 ///<param name="source"></param>
 ///<param name="separator"></param>
 ///<returns></returns>
 public static string Join(this StringCollection source, string separator)
 {
     return(string.Join(separator, source.Cast <string>()));
 }
        }         // StartSBProc

        /// <summary>
        /// Note: The behavior of the code below is really only appropriate for AudioRtr,
        /// since it kills off all of the specified components, then restarts them, which
        /// is not appropriate for AudioMgr & DialogMgr.
        /// </summary>
        /// <param name="i_XmlMsg"></param>
        /// <returns></returns>
        public bool ResetSBComponents(XmlMsg i_XmlMsg)
        {
#if (false)
            bool             bRet = true, bRes = true;
            int              iRes = -1;
            string           sComp = "", sName = "", sFile = "", sArgs = "";
            int              ii = 0, iNumComps = 0;
            StringCollection asNames = null, asFiles = null, asArgs = null;
            bool             bFound = false;

            try
            {
                sComp = i_XmlMsg.Data;
                m_Logger.Log(Level.Info, "LRMWorkerThread.ResetSBComponents: Restarting '" + sComp + "'.");
                asNames = new StringCollection();
                asFiles = new StringCollection();
                asArgs  = new StringCollection();

                // Kill off components
                do
                {
                    iRes = FindComponentInProcessList(sComp, out sFile, out sArgs);
                    if (iRes == -1)
                    {
                    }
                    else
                    {
                        bFound = true;
                        sName  = m_aProcs[iRes].Name;
                        if (m_aProcs[iRes].Running)
                        {
                            m_aProcs[iRes].Proc.EnableRaisingEvents = false;
                            m_aProcs[iRes].Proc.Exited -= new EventHandler(proc_Exited);
                            m_aProcs[iRes].Proc.Kill();
                        }
                        m_aProcs.RemoveAt(iRes);

                        // Add to list to restart (even if it didn't start before.)
                        asNames.Add(sName);
                        asFiles.Add(sFile);
                        asArgs.Add(sArgs);
                        iNumComps++;
                    }
                }while(iRes != -1);

                if (!bFound)
                {
                    m_Logger.Log(Level.Warning, "LRMWorkerThread.ResetSBComponents: Couldn't find '" + sComp + "' in the list.");
                }

                // Restart components
                for (ii = 0; ii < iNumComps; ii++)
                {
                    bRes = StartSBProc(asNames[ii], asFiles[ii], asArgs[ii]);
                }
            }
            catch (Exception exc)
            {
                bRet = false;
                m_Logger.Log(exc);
            }
#else
            bool   bRet = true;
            char   cSlash = '/';
            string sBinPath = "", sCmd = "", sArgs = "";
            System.Diagnostics.Process procCmd;

            try
            {
                // Disable raising 'exited' event
                foreach (SBProcess procChild in m_aProcs)
                {
                    procChild.Proc.EnableRaisingEvents = false;
                }

                // Format command and args
                if (RunningSystem.RunningPlatform == CLRPlatform.Mono)
                {
                    cSlash = '/';
                }
                else
                {
                    //cSlash = '\\';	// We can use '/' on Windows too.
                    cSlash = '/';
                }

                sBinPath = ConfigurationManager.AppSettings["DefaultBinPath"];
                if (!(sBinPath.EndsWith("/")) && !(sBinPath.EndsWith("\\")))
                {
                    sBinPath += cSlash;
                }
                sCmd  = sBinPath + "speechbridged";
                sArgs = "restart";

                procCmd = new Process();
                procCmd.StartInfo.FileName  = sCmd;
                procCmd.StartInfo.Arguments = sArgs;

                m_Logger.Log(Level.Debug, "LRMWorkerThread.ResetSBComponents: Starting '" + sCmd + "', '" + sArgs + "'.");

                // Run the 'reset' command
                bRet = procCmd.Start();

                Environment.Exit(0);
            }
            catch (Exception exc)
            {
                bRet = false;
                m_Logger.Log(Level.Exception, "LRMWorkerThread.ResetSBComponents caught exception: " + exc.ToString());
            }
#endif

            return(bRet);
        }         // ResetSBComponents
Beispiel #35
0
        //
        // - Methods -
        //

        /// <summary>
        /// Obsolete class, use the classes in the namespace DvtkHighLevelInterface.Common.Compare instead.
        /// <br></br>
        /// Do a dynamic compare for the attribute sets supplied.
        ///
        /// Note that the parameters attributeSets, attributeSetDescriptions and each validationRuleList instance in
        /// the parameter validationRuleLists must have the same size and have a size at least 2.
        /// </summary>
        /// <param name="tableDescription">Description of the table.</param>
        /// <param name="attributeSets">The attribute sets to compare with each other.</param>
        /// <param name="attributeSetDescriptions">The descriptions of the attribute sets.</param>
        /// <param name="validationRuleLists">
        /// Specifies which attributes with what tags should be compared with each other.
        /// Also specifies how the attributes should be compared with each other.
        /// </param>
        /// <returns>The results of the dynamic compare presented as a table (that may be converted to HTML).</returns>
        public CompareResults CompareAttributeSets(String tableDescription, ArrayList attributeSets, StringCollection attributeSetDescriptions, ArrayList validationRuleLists)
        {
            //
            // Sanity check.
            //

            if (attributeSets.Count < 2)
            {
                throw new System.Exception("Parameter attributeSets supplied to the method StaticCompare.CompareAttributeSets has size smaller than 2.");
            }

            if (attributeSets.Count != attributeSetDescriptions.Count)
            {
                throw new System.Exception("Parameters attributeSets and attributeSetDescriptions supplied to the method StaticCompare.CompareAttributeSets have different size.");
            }

            foreach (ValidationRuleList validationRuleList in validationRuleLists)
            {
                if (attributeSets.Count != validationRuleList.Count)
                {
                    throw new System.Exception("Method StaticCompare.CompareAttributeSets: each ValidationRuleList instance present in the parameter validationRuleLists must have the same size as the parameter attributeSets.");
                }
            }


            //
            // Do the actual compare.
            //

            // Start with a new empty table.
            this.compareResults = null;

            // Determine the index of the different columns in the table.
            int numberOfColumns = DetermineColumnIndices(attributeSets.Count);

            // To be able to compare correctly, we first make sure the attributes in all attributesets are ascending.
            foreach (AttributeSet attributeSet in attributeSets)
            {
                attributeSet.MakeAscending(true);
            }

            // Determine the table headers and comlumn widths.
            this.compareResults = CreateCompareResults(numberOfColumns, attributeSets.Count, tableDescription, attributeSetDescriptions);

            // Do the actual comparison.
            AddAttributeSetsInformationUsingDynamicCompare(attributeSets, validationRuleLists);

            if (this.differenceFound)
            {
                this.compareResults.DifferencesCount++;
                this.differenceFound = false;
            }

            return(this.compareResults);
        }
Beispiel #36
0
        private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames)
        {
            if (null == options)
            {
                throw new ArgumentNullException("options");
            }
            if (null == fileNames)
            {
                throw new ArgumentNullException("fileNames");
            }

            CompilerResults results = new CompilerResults(options.TempFiles);
            Process         mcs     = new Process();

            // FIXME: these lines had better be platform independent.
            if (Path.DirectorySeparatorChar == '\\')
            {
                mcs.StartInfo.FileName  = windowsMonoPath;
                mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
                                          BuildArgs(options, fileNames, ProviderOptions);
            }
            else
            {
                mcs.StartInfo.FileName  = unixMcsCommand;
                mcs.StartInfo.Arguments = BuildArgs(options, fileNames, ProviderOptions);
            }

            mcsOutput   = new StringCollection();
            mcsOutMutex = new Mutex();

/*
 *                      string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
 *                      if (monoPath != null)
 *                              monoPath = String.Empty;
 *
 *                      string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
 *                      if (privateBinPath != null && privateBinPath.Length > 0)
 *                              monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
 *
 *                      if (monoPath.Length > 0) {
 *                              StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
 *                              if (dict.ContainsKey ("MONO_PATH"))
 *                                      dict ["MONO_PATH"] = monoPath;
 *                              else
 *                                      dict.Add ("MONO_PATH", monoPath);
 *                      }
 */
            /*
             * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
             * may not handle some of the options causing compilation failure
             */
            mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;

            mcs.StartInfo.CreateNoWindow         = true;
            mcs.StartInfo.UseShellExecute        = false;
            mcs.StartInfo.RedirectStandardOutput = true;
            mcs.StartInfo.RedirectStandardError  = true;
            mcs.ErrorDataReceived += new DataReceivedEventHandler(McsStderrDataReceived);

            try {
                mcs.Start();
            } catch (Exception e) {
                Win32Exception exc = e as Win32Exception;
                if (exc != null)
                {
                    throw new SystemException(String.Format("Error running {0}: {1}", mcs.StartInfo.FileName,
                                                            Win32Exception.W32ErrorMessage(exc.NativeErrorCode)));
                }
                throw;
            }

            try {
                mcs.BeginOutputReadLine();
                mcs.BeginErrorReadLine();
                mcs.WaitForExit();

                results.NativeCompilerReturnValue = mcs.ExitCode;
            } finally {
                mcs.CancelErrorRead();
                mcs.CancelOutputRead();
                mcs.Close();
            }

            StringCollection sc = mcsOutput;

            bool loadIt = true;

            foreach (string error_line in mcsOutput)
            {
                CompilerError error = CreateErrorFromString(error_line);
                if (error != null)
                {
                    results.Errors.Add(error);
                    if (!error.IsWarning)
                    {
                        loadIt = false;
                    }
                }
            }

            if (sc.Count > 0)
            {
                sc.Insert(0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
                results.Output = sc;
            }

            if (loadIt)
            {
                if (!File.Exists(options.OutputAssembly))
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in sc)
                    {
                        sb.Append(s + Environment.NewLine);
                    }

                    throw new Exception("Compiler failed to produce the assembly. Output: '" + sb.ToString() + "'");
                }

                if (options.GenerateInMemory)
                {
                    using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        results.CompiledAssembly = Assembly.Load(buffer, null);
                        fs.Close();
                    }
                }
                else
                {
                    // Avoid setting CompiledAssembly right now since the output might be a netmodule
                    results.PathToAssembly = options.OutputAssembly;
                }
            }
            else
            {
                results.CompiledAssembly = null;
            }

            return(results);
        }
Beispiel #37
0
        static void Main(string[] argv)
        {
            Application.EnableVisualStyles();
            //把托盘图标准备好。
            iconThread = new Thread(new ThreadStart(() =>
            {
                icon         = new NotifyIcon();
                icon.Click  += icon_Click;
                icon.Icon    = XiamiSigLite.Properties.Resources.favicon;
                icon.Visible = true;
                tipShow     += new MessageHandler((msg, finished) =>
                {
                    icon.Text = msg;
                    if (finished)
                    {
                        icon.Icon = XiamiSigLite.Properties.Resources.favicon_finished;
                    }
                    else
                    {
                        icon.Icon = XiamiSigLite.Properties.Resources.favicon;
                    }
                });
                Application.Run();

                /*while (true)
                 * {
                 *  tipHandler.WaitOne();
                 *  icon.Text = currentTip.MessageText;
                 *  if (currentTip.Finished)
                 *  {
                 *      icon.Icon = XiamiSigLite.Properties.Resources.favicon_finished;
                 *  }
                 *  else
                 *  {
                 *      icon.Icon = XiamiSigLite.Properties.Resources.favicon;
                 *  }
                 *  //newTip = false;
                 * }
                 * while (true)
                 * {
                 *  exitHandler.WaitOne();
                 *  Exit(0);
                 * }*/
            }));
            iconThread.Start();

            /*//杀掉残留的家伙。
             * Process[] processes = Process.GetProcessesByName(Application.ExecutablePath.Replace(Application.StartupPath + @"\", ""));
             * try
             * {
             *  foreach (Process p in processes)
             *  {
             *      p.Kill();
             *      Popup("杀掉一只老家伙。");
             *  }
             * }
             * catch (Exception ex)
             * {
             *  Popup("杀错误:" + ex.Message);
             * }*/


            //确认数据正确性。
            if (!InfoCollector.CheckData())
            {
                Popup("请输入虾米帐户信息。");
                //Application.SetCompatibleTextRenderingDefault(true);
                if (InfoCollector.Collect())
                {
                    //真听话。
                    goto signStart;
                }
                else
                {
                    //用户在捣乱。
                    icon.Visible = false;
                    icon.Dispose();
                    Exit(1);
                }
            }

            //检查参数个数来决定是编辑信息还是直接签到。
            if (argv.Length > 0)
            {
                Console.WriteLine("虾米签到。");
            }
            else
            {
                InfoCollector.Collect();
            }
signStart:
            string email = InfoCollector.Email;
            string password = InfoCollector.Password;

            Popup();
            //icon.Click += new EventHandler();
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            //定义一些频繁用到的局部变量。
            Regex           r;
            HttpWebRequest  request;
            HttpWebResponse response;
            CookieContainer cc = new CookieContainer();

            //POST数值对。
            StringCollection names  = new StringCollection();
            StringCollection values = new StringCollection();

            names.Add("email");
            values.Add(email);
            names.Add("password");
            values.Add(password);
            names.Add("LoginButton");
            values.Add("登录");

            //把POST数值对变成字符串。
            StringBuilder postTextBuilder = new StringBuilder();

            if (names.Count == 0 || names.Count != values.Count)
            {
                Popup("登录参数错误。");
                //Thread.Sleep(10000);
                Exit(1);
            }
            for (int paraIndex = 0; paraIndex < names.Count; paraIndex++)
            {
                postTextBuilder.Append(names[paraIndex].Trim());
                postTextBuilder.Append('=');
                postTextBuilder.Append(values[paraIndex].Trim());
                postTextBuilder.Append('&');
            }
            string postText = postTextBuilder.ToString(0, postTextBuilder.Length - 1);

            //登录。
            request = (HttpWebRequest)HttpWebRequest.Create("https://login.xiami.com/web/login");
            request.CookieContainer = cc;
            request.Method          = "POST";
            request.ContentType     = "application/x-www-form-urlencoded";
            request.Referer         = "https://www.xiami.com/web"; //一字不漏。
            try
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    using (StreamWriter requestWriter = new StreamWriter(requestStream))
                    {
                        requestWriter.Write(postText);
                        requestWriter.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                Popup("登录错误:" + ex.Message);
                //Thread.Sleep(10000);
                Exit(1);
            }
            response = (HttpWebResponse)request.GetResponse();

            //得到的响应,正确的话应该是个人页。
            string loginResultText = GetStringByResponse(response);
            //loginResultText = loginResultText.Replace("null(\"", "");
            //loginResultText = loginResultText.Remove(loginResultText.Length - 2);

            //获得首页地址。
            string homeUrl = string.Empty;

            r       = new Regex("(?<=<a href=\")(.*?)(?=\">首页)");
            homeUrl = r.Match(loginResultText).Value;
            if (string.IsNullOrEmpty(homeUrl))
            {
                Popup("登陆错误:无法获得用户ID。");
                //Thread.Sleep(10000);
                Exit(1);
            }

            //Thread.Sleep(5000);

            request = (HttpWebRequest)HttpWebRequest.Create(homeUrl);
            request.CookieContainer = cc;
            response = (HttpWebResponse)request.GetResponse();
            string homeText       = GetStringByResponse(response);
            string signResultText = string.Empty;

            if (homeText.Contains("已连续签到"))
            {
                signResultText = homeText;
                goto result;
            }
            string signUrl = string.Empty;

            r       = new Regex("(?<=href=\")(.*?)(?=\">每日签到)");
            signUrl = r.Match(homeText).Value;
            signUrl = "http://www.xiami.com" + signUrl;

            //进行签到。
            request = (HttpWebRequest)HttpWebRequest.Create(signUrl);
            request.CookieContainer = cc;
            request.Referer         = "http://www.xiami.com/web"; //一字不漏。
            //request.Method = "POST";
            //request.ContentType = "application/x-www-form-urlencoded";
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex)
            {
                Popup("签到错误:" + ex.Message);
                //Thread.Sleep(10000);
                Exit(1);
            }
            //得到签到后跳转的页面。
            signResultText = GetStringByResponse(response);

            //签到正确的话应该能从页面上得到类似“已连续签到xx天”的字符串。
result:
            string dayCountText = string.Empty;

            r            = new Regex("已连续签到.*?天");
            dayCountText = r.Match(signResultText).Value;
            if (string.IsNullOrEmpty(dayCountText))
            {
                Popup("签到错误:无法得到连续签到天数。");
                //Thread.Sleep(10000);
                Exit(1);
            }
            else
            {
                Popup(dayCountText + '。', true);
                //Thread.Sleep(5000);
            }
            while (true)
            {
                exitHandler.WaitOne();
                Exit(0);
            }
            //Exit(0);
        }
Beispiel #38
0
        /// <summary> Constructor for a new instance of this class </summary>
        /// <param name="FileName"> Original file name </param>
        public Builder_SplitFileName(string FileName)
        {
            // Save the filename
            origName = FileName;

            // Create the collections for building the parts
            StringCollection parts       = new StringCollection();
            StringBuilder    partBuilder = new StringBuilder();

            // Check the first digit of the filename
            bool lastDigit = Char.IsDigit(FileName[0]);

            partBuilder.Append(FileName[0]);

            // Step through the remaining characters
            for (int i = 1; i < FileName.Length; i++)
            {
                // Underscore and dash always seperate parts
                if ((FileName[i] == '_') || (FileName[i] == '-'))
                {
                    // Only add this part, if it has length already
                    if (partBuilder.Length > 0)
                    {
                        parts.Add(partBuilder.ToString());
                        partBuilder.Remove(0, partBuilder.Length);
                    }
                }
                else
                {
                    // Check the next character to see if it is a number or not
                    bool thisDigit = Char.IsDigit(FileName[i]);

                    // If this is the same type as before, this continues the same part
                    if (thisDigit == lastDigit)
                    {
                        partBuilder.Append(FileName[i]);
                    }
                    else
                    {
                        // If there is already a part being built, make that its own part
                        if (partBuilder.Length > 0)
                        {
                            parts.Add(partBuilder.ToString());
                            partBuilder.Remove(0, partBuilder.Length);
                        }

                        // Start the next part
                        partBuilder.Append(FileName[i]);
                    }

                    // Save the digit flag
                    lastDigit = thisDigit;
                }
            }

            // Add the last part, if there was one being built
            if (partBuilder.Length > 0)
            {
                parts.Add(partBuilder.ToString());
            }

            // Fill the string array with all the parts
            nameParts = new string[parts.Count];
            for (int i = 0; i < parts.Count; i++)
            {
                nameParts[i] = parts[i];
            }
        }
Beispiel #39
0
        private static List <Tuple <ModifierKeys, Key, ShortcutCommands> > readKeyboardShortcuts(StringCollection settingsShortcuts)
        {
            List <Tuple <ModifierKeys, Key, ShortcutCommands> > result = new List <Tuple <ModifierKeys, Key, ShortcutCommands> >(settingsShortcuts.Count);

            foreach (string s in settingsShortcuts)
            {
                string[] split = s.Split(';');
                if (split.Length == 3 &&
                    Enum.TryParse(split[0], out ModifierKeys modifiers) &&
                    Enum.TryParse(split[1], out Key key) &&
                    Enum.TryParse(split[2], out ShortcutCommands command))
                {
                    result.Add(new Tuple <ModifierKeys, Key, ShortcutCommands>(modifiers, key, command));
                }
            }

            return(result);
        }
Beispiel #40
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId");
            _channelId = AuthRequest.IsQueryExists("channelId") ? AuthRequest.GetQueryInt("channelId") : SiteId;

            _isCheckOnly   = AuthRequest.GetQueryBool("isCheckOnly");
            _isTrashOnly   = AuthRequest.GetQueryBool("isTrashOnly");
            _isWritingOnly = AuthRequest.GetQueryBool("isWritingOnly");
            _isAdminOnly   = AuthRequest.GetQueryBool("isAdminOnly");

            _channelInfo = ChannelManager.GetChannelInfo(SiteId, _channelId);
            var tableName = ChannelManager.GetTableName(SiteInfo, _channelInfo);

            _relatedIdentities   = RelatedIdentities.GetChannelRelatedIdentities(SiteId, _channelId);
            _styleInfoList       = TableStyleManager.GetTableStyleInfoList(tableName, _relatedIdentities);
            _attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(ChannelManager.GetContentAttributesOfDisplay(SiteId, _channelId));
            _allStyleInfoList    = ContentUtility.GetAllTableStyleInfoList(_styleInfoList);
            _pluginMenus         = PluginContentManager.GetContentMenus(_channelInfo);
            _pluginColumns       = PluginContentManager.GetContentColumns(_channelInfo);
            _isEdit = TextUtility.IsEdit(SiteInfo, _channelId, AuthRequest.AdminPermissions);

            var state      = AuthRequest.IsQueryExists("state") ? AuthRequest.GetQueryInt("state") : CheckManager.LevelInt.All;
            var searchType = AuthRequest.IsQueryExists("searchType") ? AuthRequest.GetQueryString("searchType") : ContentAttribute.Title;
            var dateFrom   = AuthRequest.IsQueryExists("dateFrom") ? AuthRequest.GetQueryString("dateFrom") : string.Empty;
            var dateTo     = AuthRequest.IsQueryExists("dateTo") ? AuthRequest.GetQueryString("dateTo") : string.Empty;
            var keyword    = AuthRequest.IsQueryExists("keyword") ? AuthRequest.GetQueryString("keyword") : string.Empty;

            var checkedLevel = 5;
            var isChecked    = true;

            foreach (var owningChannelId in AuthRequest.AdminPermissions.OwningChannelIdList)
            {
                int checkedLevelByChannelId;
                var isCheckedByChannelId = CheckManager.GetUserCheckLevel(AuthRequest.AdminPermissions, SiteInfo, owningChannelId, out checkedLevelByChannelId);
                if (checkedLevel > checkedLevelByChannelId)
                {
                    checkedLevel = checkedLevelByChannelId;
                }
                if (!isCheckedByChannelId)
                {
                    isChecked = false;
                }
            }

            RptContents.ItemDataBound += RptContents_ItemDataBound;

            var allLowerAttributeNameList = TableMetadataManager.GetAllLowerAttributeNameListExcludeText(tableName);
            var whereString = DataProvider.ContentDao.GetPagerWhereSqlString(SiteInfo, _channelInfo,
                                                                             searchType, keyword,
                                                                             dateFrom, dateTo, state, _isCheckOnly, false, _isTrashOnly, _isWritingOnly, _isAdminOnly,
                                                                             AuthRequest.AdminPermissions,
                                                                             allLowerAttributeNameList);

            PgContents.Param = new PagerParam
            {
                ControlToPaginate = RptContents,
                TableName         = tableName,
                PageSize          = SiteInfo.Additional.PageSize,
                Page              = AuthRequest.GetQueryInt(Pager.QueryNamePage, 1),
                OrderSqlString    = ETaxisTypeUtils.GetContentOrderByString(ETaxisType.OrderByIdDesc),
                ReturnColumnNames = TranslateUtils.ObjectCollectionToString(allLowerAttributeNameList),
                WhereSqlString    = whereString,
                TotalCount        = DataProvider.DatabaseDao.GetPageTotalCount(tableName, whereString)
            };

            if (IsPostBack)
            {
                return;
            }

            if (_isTrashOnly)
            {
                if (AuthRequest.IsQueryExists("IsDeleteAll"))
                {
                    DataProvider.ContentDao.DeleteContentsByTrash(SiteId, tableName);
                    AuthRequest.AddSiteLog(SiteId, "清空回收站");
                    SuccessMessage("成功清空回收站!");
                }
                else if (AuthRequest.IsQueryExists("IsRestore"))
                {
                    var idsDictionary = ContentUtility.GetIDsDictionary(Request.QueryString);
                    foreach (var channelId in idsDictionary.Keys)
                    {
                        var contentIdArrayList = idsDictionary[channelId];
                        DataProvider.ContentDao.TrashContents(SiteId, ChannelManager.GetTableName(SiteInfo, channelId), contentIdArrayList);
                    }
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原内容");
                    SuccessMessage("成功还原内容!");
                }
                else if (AuthRequest.IsQueryExists("IsRestoreAll"))
                {
                    DataProvider.ContentDao.RestoreContentsByTrash(SiteId, tableName);
                    AuthRequest.AddSiteLog(SiteId, "从回收站还原所有内容");
                    SuccessMessage("成功还原所有内容!");
                }
            }

            ChannelManager.AddListItems(DdlChannelId.Items, SiteInfo, true, true, AuthRequest.AdminPermissions);

            CheckManager.LoadContentLevelToList(DdlState, SiteInfo, _isCheckOnly, isChecked, checkedLevel);
            ControlUtils.SelectSingleItem(DdlState, state.ToString());

            foreach (var styleInfo in _allStyleInfoList)
            {
                if (styleInfo.InputType == InputType.TextEditor)
                {
                    continue;
                }

                var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName);
                DdlSearchType.Items.Add(listitem);
            }

            //ETriStateUtils.AddListItems(DdlState, "全部", "已审核", "待审核");

            if (SiteId != _channelId)
            {
                ControlUtils.SelectSingleItem(DdlChannelId, _channelId.ToString());
            }
            //ControlUtils.SelectSingleItem(DdlState, AuthRequest.GetQueryString("State"));
            ControlUtils.SelectSingleItem(DdlSearchType, searchType);
            TbKeyword.Text  = keyword;
            TbDateFrom.Text = dateFrom;
            TbDateTo.Text   = dateTo;

            PgContents.DataBind();

            LtlColumnsHead.Text += TextUtility.GetColumnsHeadHtml(_styleInfoList, _pluginColumns, _attributesOfDisplay);


            BtnSelect.Attributes.Add("onclick", ModalSelectColumns.GetOpenWindowString(SiteId, _channelId));

            if (_isTrashOnly)
            {
                LtlColumnsHead.Text  += @"<th class=""text-center text-nowrap"" width=""150"">删除时间</th>";
                BtnAddToGroup.Visible = BtnTranslate.Visible = BtnCheck.Visible = false;
                PhTrash.Visible       = true;
                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentDelete))
                {
                    BtnDelete.Visible    = false;
                    BtnDeleteAll.Visible = false;
                }
                else
                {
                    BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, true, PageUrl));
                    BtnDeleteAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsDeleteAll", "True"), "确实要清空回收站吗?"));
                }
                BtnRestore.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValue(PageUtils.AddQueryString(PageUrl, "IsRestore", "True"), "IDsCollection", "IDsCollection", "请选择需要还原的内容!"));
                BtnRestoreAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsRestoreAll", "True"), "确实要还原所有内容吗?"));
            }
            else
            {
                LtlColumnsHead.Text += @"<th class=""text-center text-nowrap"" width=""100"">操作</th>";

                BtnAddToGroup.Attributes.Add("onclick", ModalAddToGroup.GetOpenWindowStringToContentForMultiChannels(SiteId));

                if (HasChannelPermissions(SiteId, ConfigManager.ChannelPermissions.ContentCheck))
                {
                    BtnCheck.Attributes.Add("onclick", ModalContentCheck.GetOpenWindowStringForMultiChannels(SiteId, PageUrl));
                    if (_isCheckOnly)
                    {
                        BtnCheck.CssClass = "btn m-r-5 btn-success";
                    }
                }
                else
                {
                    PhCheck.Visible = false;
                }

                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentTranslate))
                {
                    BtnTranslate.Visible = false;
                }
                else
                {
                    BtnTranslate.Attributes.Add("onclick", PageContentTranslate.GetRedirectClickStringForMultiChannels(SiteId, PageUrl));
                }

                if (!HasChannelPermissions(_channelId, ConfigManager.ChannelPermissions.ContentDelete))
                {
                    BtnDelete.Visible = false;
                }
                else
                {
                    BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, false, PageUrl));
                }
            }
        }
Beispiel #41
0
 public string Paste(string target, StringCollection items, FileAction action, short flags = ShellNative.FOF_ALLOWUNDO)
 {
     return(PasteAction.Paste(target, items, action, flags));
 }
Beispiel #42
0
 public string Move(string target, StringCollection items)
 {
     return(Paste(target, items, FileAction.Move));
 }
Beispiel #43
0
 public string GetPhpScriptReferenceCode(StringCollection code)
 {
     return(CodeName);
 }
Beispiel #44
0
        public static string GetColumnsHtml(Dictionary<string, string> nameValueCacheDict, SiteInfo siteInfo, ContentInfo contentInfo, StringCollection attributesOfDisplay, List<TableStyleInfo> displayStyleInfoList)
        {
            var builder = new StringBuilder();

            foreach (var styleInfo in displayStyleInfoList)
            {
                if (!attributesOfDisplay.Contains(styleInfo.AttributeName)) continue;

                var value = GetColumnValue(nameValueCacheDict, siteInfo, contentInfo, styleInfo);
                builder.Append($@"<td class=""text-nowrap"">{value}</td>");
            }

            return builder.ToString();
        }
Beispiel #45
0
        public static void Main(string[] args)
        {
            try
            {
                new TAppSettingsManager(false);

                if (Directory.Exists("log"))
                {
                    new TLogging("log/generatewinforms.log");
                }
                else
                {
                    new TLogging("generatewinforms.log");
                }

                TLogging.DebugLevel = TAppSettingsManager.GetInt16("Server.DebugLevel", 0);

                if (!TAppSettingsManager.HasValue("op"))
                {
                    Console.WriteLine("call: GenerateWinForms -op:generate -ymlfile:c:\\test.yaml -petraxml:petra.xml -localisation:en");
                    Console.WriteLine("  or: GenerateWinForms -op:generate -ymldir:c:\\myclient -petraxml:petra.xml -localisation:en");
                    Console.WriteLine("  or: GenerateWinForms -op:clean -ymldir:c:\\myclient");
                    Console.WriteLine("  or: GenerateWinForms -op:preview");
                    Console.Write("Press any key to continue . . . ");
                    Console.ReadLine();
                    Environment.Exit(-1);
                    return;
                }

                // calculate ICTPath from ymlfile path
                string fullYmlfilePath =
                    Path.GetFullPath(TAppSettingsManager.GetValue("ymlfile", TAppSettingsManager.GetValue("ymldir", false))).Replace(
                        "\\",
                        "/");

                if (!fullYmlfilePath.Contains("csharp/ICT"))
                {
                    Console.WriteLine("ymlfile must be below the csharp/ICT directory");
                }

                CSParser.ICTPath = fullYmlfilePath.Substring(0, fullYmlfilePath.IndexOf("csharp/ICT") + "csharp/ICT".Length);

                if (TAppSettingsManager.GetValue("op") == "clean")
                {
                    if (!Directory.Exists(fullYmlfilePath))
                    {
                        throw new Exception("invalid directory " + fullYmlfilePath);
                    }

                    // delete all generated files in the directory
                    foreach (string file in System.IO.Directory.GetFiles(fullYmlfilePath, "*.yaml", SearchOption.AllDirectories))
                    {
                        DeleteGeneratedFile(file, "-generated.cs");
                        DeleteGeneratedFile(file, "-generated.Designer.cs");
                        DeleteGeneratedFile(file, "-generated.resx");
                    }
                }
                else if (TAppSettingsManager.GetValue("op") == "preview")
                {
                    string SelectedLocalisation = null;         // none selected by default; winforms autosize works quite well

                    if (TAppSettingsManager.HasValue("localisation"))
                    {
                        SelectedLocalisation = TAppSettingsManager.GetValue("localisation");
                    }

                    TDataBinding.FPetraXMLStore = new TDataDefinitionStore();
                    Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true));
                    TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true));
                    parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true);

                    TFrmYamlPreview PreviewWindow = new TFrmYamlPreview(
                        TAppSettingsManager.GetValue("ymlfile"),
                        SelectedLocalisation);

                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
                    Application.ThreadException += new ThreadExceptionEventHandler(UnhandledThreadExceptionHandler);

                    PreviewWindow.ShowDialog();

                    return;
                }
                else if (TAppSettingsManager.GetValue("op") == "generate")
                {
                    string SelectedLocalisation = null;         // none selected by default; winforms autosize works quite well

                    if (TAppSettingsManager.HasValue("localisation"))
                    {
                        SelectedLocalisation = TAppSettingsManager.GetValue("localisation");
                    }

                    TDataBinding.FPetraXMLStore = new TDataDefinitionStore();
                    Console.WriteLine("parsing " + TAppSettingsManager.GetValue("petraxml", true));
                    TDataDefinitionParser parser = new TDataDefinitionParser(TAppSettingsManager.GetValue("petraxml", true));
                    parser.ParseDocument(ref TDataBinding.FPetraXMLStore, true, true);

                    string ymlfileParam = TAppSettingsManager.GetValue("ymlfile", TAppSettingsManager.GetValue("ymldir", false));

                    if (ymlfileParam.Contains(","))
                    {
                        StringCollection collection = StringHelper.StrSplit(ymlfileParam, ",");

                        foreach (string file in collection)
                        {
                            ProcessFile(file, SelectedLocalisation);
                        }
                    }
                    else if (System.IO.Directory.Exists(ymlfileParam))
                    {
                        string[] yamlfiles = System.IO.Directory.GetFiles(ymlfileParam, "*.yaml", SearchOption.AllDirectories);
                        // sort the files so that the deepest files are first processed,
                        // since the files higher up are depending on them
                        // eg. FinanceMain.yaml needs to check for GLBatch-generated.cs

                        List <string> yamlFilesSorted = new List <string>(yamlfiles.Length);

                        foreach (string file in yamlfiles)
                        {
                            yamlFilesSorted.Add(file);
                        }

                        yamlFilesSorted.Sort(new YamlFileOrderComparer());

                        foreach (string file in yamlFilesSorted)
                        {
                            // only look for main files, not language specific files (*.xy-XY.yaml or *.xy.yaml)
                            if (TProcessYAMLForms.IgnoreLanguageSpecificYamlFile(file))
                            {
                                continue;
                            }

                            Console.WriteLine("working on " + file);
                            ProcessFile(file, SelectedLocalisation);
                        }
                    }
                    else
                    {
                        ProcessFile(ymlfileParam, SelectedLocalisation);
                    }
                }
            }
            catch (Exception e)
            {
                string commandline = "";

                foreach (string s in args)
                {
                    commandline += s + " ";
                }

                Console.WriteLine("Problem while processing " + commandline);
                Console.WriteLine(e.GetType().ToString() + ": " + e.Message);

                if (e.InnerException != null)
                {
                    Console.WriteLine(e.InnerException.GetType().ToString() + ": " + e.InnerException.Message);
                }

                // do not print a stacktrace for custom generated exception, eg. by the YML parser
                if ((e.GetType() != typeof(System.Exception)) || (TLogging.DebugLevel > 0))
                {
                    Console.WriteLine(e.StackTrace);
                }

                Environment.Exit(-1);
            }
        }
Beispiel #46
0
        /// <summary>
        /// write to the output interface
        /// </summary>
        private void WriteToScreen()
        {
            int leftIndentation      = _indentationManager.LeftIndentation;
            int rightIndentation     = _indentationManager.RightIndentation;
            int firstLineIndentation = _indentationManager.FirstLineIndentation;

            // VALIDITY CHECKS:

            // check the useful ("active") width
            int usefulWidth = _textColumns - rightIndentation - leftIndentation;

            if (usefulWidth <= 0)
            {
                // fatal error, there is nothing to write to the device
                // just clear the buffer and return
                _stringBuffer = new StringBuilder();
            }

            // check indentation or hanging is not larger than the active width
            int indentationAbsoluteValue = (firstLineIndentation > 0) ? firstLineIndentation : -firstLineIndentation;

            if (indentationAbsoluteValue >= usefulWidth)
            {
                // valu too big, we reset it to zero
                firstLineIndentation = 0;
            }


            // compute the first line indentation or hanging
            int firstLineWidth      = _textColumns - rightIndentation - leftIndentation;
            int followingLinesWidth = firstLineWidth;

            if (firstLineIndentation >= 0)
            {
                // the first line has an indentation
                firstLineWidth -= firstLineIndentation;
            }
            else
            {
                // the first line is hanging
                followingLinesWidth += firstLineIndentation;
            }

            //error checking on invalid values

            // generate the lines using the computed widths
            StringCollection sc = StringManipulationHelper.GenerateLines(_lo.DisplayCells, _stringBuffer.ToString(),
                                                                         firstLineWidth, followingLinesWidth);

            // compute padding
            int firstLinePadding      = leftIndentation;
            int followingLinesPadding = leftIndentation;

            if (firstLineIndentation >= 0)
            {
                // the first line has an indentation
                firstLinePadding += firstLineIndentation;
            }
            else
            {
                // the first line is hanging
                followingLinesPadding -= firstLineIndentation;
            }

            // now write the lines on the screen
            bool firstLine = true;

            foreach (string s in sc)
            {
                if (firstLine)
                {
                    firstLine = false;
                    _lo.WriteLine(StringManipulationHelper.PadLeft(s, firstLinePadding));
                }
                else
                {
                    _lo.WriteLine(StringManipulationHelper.PadLeft(s, followingLinesPadding));
                }
            }

            _stringBuffer = new StringBuilder();
        }
Beispiel #47
0
 public UndoCopyAction(string path, StringCollection items)
 {
     _path  = path;
     _items = items;
 }
Beispiel #48
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);
        }
Beispiel #49
0
        private void scriptall()
        {
            stroutput = new StringBuilder();

            //生成表脚本
            #region 生成表脚本
            output.AppendText("\r\n");
            output.AppendText("--以下为表对象脚本\r\n");
            output.AppendText("\r\n");

            foreach (Table tb in db.Tables)
            {
                if (!tb.IsSystemObject && !inreftables(tb.Name, reftables))
                {
                    scripttable(tb);
                }
            }
            output.AppendText("\r\n");
            output.AppendText("--以上为表对象脚本\r\n");
            output.AppendText("\r\n");
            #endregion
            #region 生成存储过程脚本



            output.AppendText("\r\n");
            output.AppendText("--以下为存储过程对象脚本\r\n");
            output.AppendText("\r\n");

            foreach (StoredProcedure proc in db.StoredProcedures)
            {
                if (!proc.IsSystemObject)
                {
                    stroutput = new StringBuilder();

                    stroutput.AppendLine();
                    stroutput.AppendLine("--存储过程[" + proc.Name + "]脚本");

                    if (!proc.IsEncrypted)
                    {
                        strColl = proc.Script(scpopt);

                        foreach (String str in strColl)
                        {
                            stroutput.AppendLine(str);
                            stroutput.AppendLine("GO");
                        }
                    }
                    else
                    {
                        stroutput.AppendLine();
                        stroutput.AppendLine("--存储过程被加密");
                        stroutput.AppendLine();
                    }
                    output.AppendText(stroutput.ToString());
                    stroutput = new StringBuilder();
                }
            }
            output.AppendText("\r\n");
            output.AppendText("--以上为存储过程对象脚本\r\n");
            output.AppendText("\r\n");
            #endregion

            #region 生成函数过程脚本
            output.AppendText("\r\n");
            output.AppendText("--以下为函数对象脚本\r\n");
            output.AppendText("\r\n");
            foreach (UserDefinedFunction func in db.UserDefinedFunctions)
            {
                if (!func.IsSystemObject)
                {
                    stroutput = new StringBuilder();

                    stroutput.AppendLine();
                    stroutput.AppendLine("--函数[" + func.Name + "]脚本");

                    if (!func.IsEncrypted)
                    {
                        strColl = func.Script(scpopt);

                        foreach (String str in strColl)
                        {
                            stroutput.AppendLine(str);
                            stroutput.AppendLine("GO");
                        }
                    }
                    else
                    {
                        stroutput.AppendLine("--函数被加密");
                        stroutput.AppendLine();
                    }
                    output.AppendText(stroutput.ToString());
                    SaveFile(stroutput.ToString(), txtSaveDir.Text + "\\" + svr.Name.Replace(",7001", string.Empty) + "_" + db.Name + ".fuc");
                    stroutput = new StringBuilder();
                }
            }
            output.AppendText("\r\n");
            output.AppendText("--以上为函数对象脚本\r\n");
            output.AppendText("\r\n");
            #endregion

            #region 生成视图过程脚本

            output.AppendText("\r\n");
            output.AppendText("--以下为视图对象脚本\r\n");
            output.AppendText("\r\n");
            foreach (Microsoft.SqlServer.Management.Smo.View viw in db.Views)
            {
                if (!viw.IsSystemObject)
                {
                    stroutput = new StringBuilder();
                    stroutput.AppendLine();
                    stroutput.AppendLine("--视图[" + viw.Name + "]脚本");

                    if (!viw.IsEncrypted)
                    {
                        strColl = viw.Script(scpopt);

                        foreach (String str in strColl)
                        {
                            stroutput.AppendLine(str);
                            stroutput.AppendLine("GO");
                        }
                    }
                    else
                    {
                        stroutput.AppendLine("--视图被加密");
                        stroutput.AppendLine();
                    }
                    output.AppendText(stroutput.ToString());
                    stroutput = new StringBuilder();
                }
            }
            output.AppendText("\r\n");
            output.AppendText("--以上为视图对象脚本\r\n");
            output.AppendText("\r\n");
            #endregion
            #region 安全性

            //用户
            output.AppendText("\r\n");
            output.AppendText("--以下为数据库用户对象脚本\r\n");
            output.AppendText("\r\n");
            foreach (User user in db.Users)
            {
                if (!user.IsSystemObject)
                {
                    stroutput = new StringBuilder();

                    stroutput.AppendLine();
                    stroutput.AppendLine("--数据库用户[" + user.Name + "]脚本");

                    foreach (string str in user.Script(scpopt))
                    {
                        stroutput.AppendLine(str);
                        stroutput.AppendLine("GO");
                    }
                    foreach (string str in user.EnumRoles())
                    {
                        stroutput.AppendLine("EXEC sp_addrolemember N'" + str + "', N'" + user.Name + "'");
                        stroutput.AppendLine("GO");
                    }
                    output.AppendText(stroutput.ToString());
                    SaveFile(stroutput.ToString(), txtSaveDir.Text + "\\" + svr.Name.Replace(",7001", string.Empty) + "_" + db.Name + ".usr");
                    stroutput = new StringBuilder();
                }
            }
            output.AppendText("\r\n");
            output.AppendText("--以上为数据库用户对象脚本\r\n");
            output.AppendText("\r\n");
            //角色
            output.AppendText("\r\n");
            output.AppendText("--以下为数据库角色对象脚本\r\n");
            output.AppendText("\r\n");
            foreach (DatabaseRole role in db.Roles)
            {
                if (!role.IsFixedRole)
                {
                    stroutput = new StringBuilder();

                    stroutput.AppendLine();
                    stroutput.AppendLine("--数据库角色[" + role.Name + "]脚本");

                    foreach (string str in role.Script(scpopt))
                    {
                        stroutput.AppendLine(str);
                        stroutput.AppendLine("GO");
                    }
                    output.AppendText(stroutput.ToString());
                    SaveFile(stroutput.ToString(), txtSaveDir.Text + "\\" + svr.Name.Replace(",7001", string.Empty) + "_" + db.Name + ".rol");
                    stroutput = new StringBuilder();
                }
            }
            output.AppendText("\r\n");
            output.AppendText("--以上为数据库角色对象脚本\r\n");
            output.AppendText("\r\n");

            #endregion
        }
Beispiel #50
0
 internal SplitLinesAccumulator(StringCollection retVal, int firstLineLen, int followingLinesLen)
 {
     _retVal            = retVal;
     _firstLineLen      = firstLineLen;
     _followingLinesLen = followingLinesLen;
 }
        }         // MsgLoop

        public bool StartSBComponents()
        {
            bool             bRet = true, bRes = true;
            string           sStarts = "";
            StringCollection asBins = null, asMonoBins = null;
            StringBuilder    sbLauncherApps = null;
            int           ii, iMaxSessions = 0;
            string        sMonoBinPath = "", sBinPath = "", sCfgPath = "", sLogPath = "";
            string        sCmd = "";
            StringBuilder sbArgs = null;
            char          cSlash;

            string[] asLauncherSupportedApps  = { m_csAppNameAudiortr };                                                // FIX:  This should instead by initialized by calling `SBLauncher --supported` and reading in the results from stdin.
            bool     bLauncherStartedAudiortr = false;

            try
            {
                if (RunningSystem.RunningPlatform == CLRPlatform.Mono)
                {
                    cSlash = '/';
                }
                else
                {
                    //cSlash = '\\';	// We can use '/' on Windows too.
                    cSlash = '/';
                }

                sMonoBinPath = ConfigurationManager.AppSettings["MonoBinPath"];
                if (!(sMonoBinPath.EndsWith("/")) && !(sMonoBinPath.EndsWith("\\")))
                {
                    sMonoBinPath += cSlash;
                }
                sBinPath = ConfigurationManager.AppSettings["DefaultBinPath"];
                if (!(sBinPath.EndsWith("/")) && !(sBinPath.EndsWith("\\")))
                {
                    sBinPath += cSlash;
                }

                if (m_bDesktopRuntime == true)
                {
                    sMonoBinPath += "mono " + SBLocalRM.g_sDesktopArg + " " + sBinPath;
                }
                else
                {
                    sMonoBinPath += "mono " + sBinPath;
                }

                sLogPath = ConfigurationManager.AppSettings["DefaultLogFilePath"];
                if (!(sLogPath.EndsWith("/")) && !(sLogPath.EndsWith("\\")))
                {
                    sLogPath += cSlash;
                }

                sCfgPath = ConfigurationManager.AppSettings["DefaultConfigPath"];
                if (!(sCfgPath.EndsWith("/")) && !(sCfgPath.EndsWith("\\")))
                {
                    sCfgPath += cSlash;
                }

                iMaxSessions = ConfigParams.GetNumExt();

                // Binary executables to start
                asBins  = new StringCollection();
                sStarts = ConfigurationManager.AppSettings["BinsToStart"];
                bRes    = Utilities.GetItemsFromString(sStarts, ';', asBins);

                // Mono binaries to start
                asMonoBins = new StringCollection();
                sStarts    = ConfigurationManager.AppSettings["MonoBinsToStart"];
                bRes       = Utilities.GetItemsFromString(sStarts, ';', asMonoBins);

                sbArgs = new StringBuilder();

                // Launch Mono executables
                try
                {
                    if (asMonoBins.Contains(m_csAppNameAudiomgr))
                    {
                        sbArgs.Length = 0;
//						sCmd = sMonoBinPath + "AudioMgr.exe";
                        sCmd = sBinPath + "AudioMgr.sh";                                                // Launch script to get around bug introduced in Mono 2.6.3 where Mono EXEs fail to launch directly.  FIX - Change this back once they fix it, we don't want the extra 'sh' overhead.

                        /* Redirection like this doesn't work on mono/linux
                         * sCmd += " >/dev/null";	// FIX - won't work on Mono for Windows
                         *
                         * if(sLogPath.Length > 0)
                         * {
                         *      sbArgs.AppendFormat(" 2>>{0}AudioMgr.stderr.log", sLogPath);
                         * }
                         * else
                         * {
                         *      sbArgs.AppendFormat("2>>/home/speechbridge/logs/AudioMgr.stderr.log");	// FIX - Won't work on Mono for Windows
                         * }
                         */

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameAudiomgr, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }
                try
                {
                    if (asMonoBins.Contains(m_csAppNameDialogmgr))
                    {
                        sbArgs.Length = 0;
//						sCmd = sMonoBinPath + "DialogMgr.exe";
                        sCmd = sBinPath + "DialogMgr.sh";                                               // Launch script to get around bug introduced in Mono 2.6.3 where Mono EXEs fail to launch directly.  FIX - Change this back once they fix it, we don't want the extra 'sh' overhead.

                        /*
                         * sCmd += " >/dev/null";	// FIX - won't work on Mono for Windows
                         *
                         * if(sLogPath.Length > 0)
                         * {
                         *      sbArgs.AppendFormat("2>>{0}DialogMgr.stderr.log", sLogPath);
                         * }
                         * else
                         * {
                         *      sbArgs.AppendFormat("2>>/home/speechbridge/logs/DialogMgr.stderr.log");
                         * }
                         */

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameDialogmgr, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }
                try
                {
                    if (asMonoBins.Contains(m_csAppNameSbsched))
                    {
                        sbArgs.Length = 0;
//						sCmd = sMonoBinPath + "SBSched.exe";
                        sCmd = sBinPath + "SBSched.sh";                                         // Launch script to get around bug introduced in Mono 2.6.3 where Mono EXEs fail to launch directly.  FIX - Change this back once they fix it, we don't want the extra 'sh' overhead.

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameSbsched, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }

                // Launch executables	// FIX - Check that Mono bins aren't here?  (I.e., config file error)
                try
                {
                    if (asBins.Contains(m_csAppNameAudiomgr))
                    {
                        sbArgs.Length = 0;
                        sCmd          = sBinPath + "AudioMgr.exe";

                        /* Redirection like this doesn't work on mono/linux
                         * if(sLogPath.Length > 0)
                         * {
                         *      sbArgs.AppendFormat("2>>{0}AudioMgr.stderr.log", sLogPath);
                         * }
                         */

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameAudiomgr, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }
                try
                {
                    if (asBins.Contains(m_csAppNameDialogmgr))
                    {
                        sbArgs.Length = 0;
                        sCmd          = sBinPath + "DialogMgr.exe";

                        /* Redirection like this doesn't work on mono/linux
                         * if(sLogPath.Length > 0)
                         * {
                         *      sbArgs.AppendFormat("2>>{0}DialogMgr.stderr.log", sLogPath);
                         * }
                         */

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameDialogmgr, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }
                try
                {
                    if (asBins.Contains(m_csAppNameSbsched))
                    {
                        sbArgs.Length = 0;
                        sCmd          = sBinPath + "SBSched.exe";

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameSbsched, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }

                // Launch SIP Proxy server
                try
                {
                    if (asBins.Contains(m_csAppNameProxysrv))
                    {
                        sbArgs.Length = 0;
                        sCmd          = sBinPath + m_csAppNameProxysrv;
                        sbArgs.AppendFormat("-x -i {0}ProxySrv.config -l {1}ProxySrv.log", sCfgPath, sLogPath);

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameProxysrv, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }

                // Start SBLauncher.  For now, this should be second to last, since it is only starting AudioRtr.
                // FIX:  If it takes on more launching duties, it should be moved accordingly.
                try
                {
                    if (asBins.Contains(m_csAppNameSblauncher))
                    {
                        sbLauncherApps = new StringBuilder();
                        for (ii = 0; ii < asLauncherSupportedApps.Length; ii++)
                        {
                            if (asBins.Contains(asLauncherSupportedApps[ii]))
                            {
                                sbLauncherApps.Append(asLauncherSupportedApps[ii]);
                                sbLauncherApps.Append(' ');

                                if (asLauncherSupportedApps[ii] == m_csAppNameAudiortr)
                                {
                                    bLauncherStartedAudiortr = true;
                                }
                            }
                            else
                            {
                                m_Logger.Log(Level.Warning, "LWT.StartSBComponents: Unsupported app '" + asLauncherSupportedApps[ii] + "'.");
                            }
                        }
                        sbArgs.Length = 0;
                        sCmd          = sBinPath + m_csAppNameSblauncher;
                        sbArgs.AppendFormat("{0} {1} {2} {3} {4}", iMaxSessions, sBinPath, sCfgPath, sLogPath, sbLauncherApps.ToString());

                        m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                        bRes = StartSBProc(m_csAppNameSblauncher, sCmd, sbArgs.ToString());
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }

                // Launch AudioRtrs last
                try
                {
                    if (!bLauncherStartedAudiortr && asBins.Contains(m_csAppNameAudiortr))
                    {
                        for (ii = 0; ii < iMaxSessions; ii++)
                        {
                            sbArgs.Length = 0;

                            //sCmd = sBinPath + "gua";
                            sCmd = sBinPath + m_csAppNameAudiortr;

                            //sbArgs.AppendFormat("-f {0}{1}.cfg >>{2}AudioRtr_p{3}.log 2>>{4}AudioRtr_p{5}.stderr.log", sCfgPath, ii, sLogPath, ii, sLogPath, ii);
                            sbArgs.AppendFormat("-f {0}{1}.cfg", sCfgPath, ii);

                            m_Logger.Log(Level.Debug, "LRMWorkerThread.StartSBComponents: Starting '" + sCmd + " " + sbArgs.ToString() + "'.");
                            bRes = StartSBProc(m_csAppNameAudiortr, sCmd, sbArgs.ToString());
                        }
                    }
                }
                catch (Exception exc)
                {
                    m_Logger.Log(exc);
                }
            }
            catch (Exception exc)
            {
                bRet = false;
                m_Logger.Log(exc);
            }

            return(bRet);
        }         // StartSBComponents
Beispiel #52
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);
        }
Beispiel #53
0
        public bool SectionExists(string Section)
        {
            StringCollection stringCollection = ReadSections();

            return(stringCollection.IndexOf(Section) > -1);
        }
Beispiel #54
0
        public bool ValueExists(string Section, string Ident)
        {
            StringCollection stringCollection = ReadSection(Section);

            return(stringCollection.IndexOf(Ident) > -1);
        }
Beispiel #55
0
        //
        // ProcessGetCounter()
        // Does the work to process GetCounterSet parameter set.
        //
        private void ProcessGetCounter()
        {
            // 1. Combine machine names with paths, if needed, to construct full paths
            // 2. Translate default paths into current locale
            // 3. Expand wildcards and validate the paths and write errors for any invalid paths
            // 4. OpenQuery/ AddCounters
            // 5. Skip the first reading

            CultureInfo culture = GetCurrentCulture();
            List <Tuple <char, char> > characterReplacementList = null;
            List <string> paths = CombineMachinesAndCounterPaths();
            uint          res   = 0;

            if (!_defaultCounters)
            {
                _cultureAndSpecialCharacterMap.TryGetValue(culture.Name, out characterReplacementList);
            }


            StringCollection allExpandedPaths = new StringCollection();

            foreach (string path in paths)
            {
                string localizedPath = path;
                if (_defaultCounters)
                {
                    res = _pdhHelper.TranslateLocalCounterPath(path, out localizedPath);
                    if (res != 0)
                    {
                        string    msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathTranslationFailed"), res);
                        Exception exc = new Exception(msg);
                        WriteError(new ErrorRecord(exc, "CounterPathTranslationFailed", ErrorCategory.InvalidResult, null));

                        localizedPath = path;
                    }
                }
                else if (characterReplacementList != null)
                {
                    foreach (Tuple <char, char> pair in characterReplacementList)
                    {
                        localizedPath = localizedPath.Replace(pair.Item1, pair.Item2);
                    }
                }

                StringCollection expandedPaths;
                res = _pdhHelper.ExpandWildCardPath(localizedPath, out expandedPaths);
                if (res != 0)
                {
                    WriteDebug("Could not expand path " + localizedPath);
                    ReportPdhError(res, false);
                    continue;
                }

                foreach (string expandedPath in expandedPaths)
                {
                    if (!_pdhHelper.IsPathValid(expandedPath))
                    {
                        string    msg = string.Format(CultureInfo.CurrentCulture, _resourceMgr.GetString("CounterPathIsInvalid"), localizedPath);
                        Exception exc = new Exception(msg);
                        WriteError(new ErrorRecord(exc, "CounterPathIsInvalid", ErrorCategory.InvalidResult, null));

                        continue;
                    }
                    allExpandedPaths.Add(expandedPath);
                }
            }
            if (allExpandedPaths.Count == 0)
            {
                return;
            }

            res = _pdhHelper.OpenQuery();
            if (res != 0)
            {
                ReportPdhError(res, false);
            }
            res = _pdhHelper.AddCounters(ref allExpandedPaths, true);
            if (res != 0)
            {
                ReportPdhError(res, true);

                return;
            }

            PerformanceCounterSampleSet nextSet;

            bool bSkip       = true;
            uint sampleReads = 0;

            if (Continuous.IsPresent)
            {
                _maxSamples = KEEP_ON_SAMPLING;
            }

            while (true)
            {
                // read the first set just to get the initial values
                res = _pdhHelper.ReadNextSet(out nextSet, bSkip);

                if (res == 0)
                {
                    //Display valid data
                    if (!bSkip)
                    {
                        WriteSampleSetObject(nextSet);
                        sampleReads++;
                    }

                    //Don't need to skip anymore
                    bSkip = false;
                }
                else if (res == PdhResults.PDH_NO_DATA || res == PdhResults.PDH_INVALID_DATA)
                {
                    // The provider may not be running.
                    // We should keep on trying - but skip the next valid reading.

                    ReportPdhError(res, false);

                    bSkip = true;

                    // Count this failed attempt as a sample:
                    sampleReads++;
                }
                else
                {
                    // Unexpected error, return
                    ReportPdhError(res, true);
                    return;
                }

                if (_maxSamples != KEEP_ON_SAMPLING && sampleReads >= _maxSamples)
                {
                    break;
                }

#if CORECLR
                // CoreCLR has no overload of WaitOne with (interval, exitContext)
                bool cancelled = _cancelEventArrived.WaitOne((int)_sampleInterval * 1000);
#else
                bool cancelled = _cancelEventArrived.WaitOne((int)_sampleInterval * 1000, true);
#endif
                if (cancelled)
                {
                    break;
                }
            }
        }
        private void DoFilter(bool notUseCache)
        {
            string cacheKey;

            common.myKeyValueExt     item          = (common.myKeyValueExt)common.Threading.GetValue(codeGroupCb, "SelectedItem");
            cbStockSelection.Options watchListType = (cbStockSelection.Options) byte.Parse(item.Attribute1);
            StringCollection         stocCodeList  = new StringCollection();

            myStockTbl.Columns[myStockTbl.selectedColumn.ColumnName].ReadOnly = false;
            switch (watchListType)
            {
            case cbStockSelection.Options.All:
                stockSource.Filter = "";
                break;

            case cbStockSelection.Options.StockExchange:
                stockSource.Filter = this.myStockTbl.stockExchangeColumn.ColumnName + "='" + item.Value + "'";
                break;

            case cbStockSelection.Options.SysWatchList:
            case cbStockSelection.Options.WatchList:

                cacheKey = watchListType.ToString();;
                StringCollection watchList = new StringCollection();
                //All stock codes of  specified type ??
                if (item.Value != "")
                {
                    cacheKey += "-" + item.Value;
                    watchList.Add(item.Value);
                }
                else
                {
                    for (int idx = 0; idx < codeGroupCb.Items.Count; idx++)
                    {
                        common.myKeyValueExt tmpItem = (common.myKeyValueExt)codeGroupCb.Items[idx];
                        if (watchListType != (cbStockSelection.Options) byte.Parse(tmpItem.Attribute1) || (tmpItem.Value == ""))
                        {
                            continue;
                        }
                        watchList.Add(tmpItem.Value);
                    }
                }
                cacheKey = DataAccess.Libs.MakeCacheKey(this, cacheKey);
                if (notUseCache)
                {
                    DataAccess.Libs.ClearCache(cacheKey);
                }
                StringCollection selectStockList = null;
                object           obj             = DataAccess.Libs.GetCache(cacheKey);
                if (obj != null)
                {
                    selectStockList = (obj as StringCollection);
                }
                else
                {
                    selectStockList = common.system.List2Collection(DataAccess.Libs.GetStockList_ByWatchList(watchList));
                    DataAccess.Libs.AddCache(cacheKey, selectStockList);
                }
                for (int idx = 0; idx < this.myStockTbl.Count; idx++)
                {
                    this.myStockTbl[idx].selected = (selectStockList.Contains(this.myStockTbl[idx].code)?1:0);
                }
                stockSource.Filter = this.myStockTbl.selectedColumn + "=1";
                break;


            case cbStockSelection.Options.UserPorfolio:
                cacheKey = watchListType.ToString();;
                StringCollection porfolioList = new StringCollection();
                //All stock codes of the specified type ??
                if (item.Value != "")
                {
                    cacheKey += "-" + item.Value;
                    porfolioList.Add(item.Value);
                }
                else
                {
                    for (int idx = 0; idx < codeGroupCb.Items.Count; idx++)
                    {
                        common.myKeyValueExt tmpItem = (common.myKeyValueExt)codeGroupCb.Items[idx];
                        if (watchListType != (cbStockSelection.Options) byte.Parse(tmpItem.Attribute1) || (tmpItem.Value == ""))
                        {
                            continue;
                        }
                        porfolioList.Add(tmpItem.Value);
                    }
                }
                cacheKey = DataAccess.Libs.MakeCacheKey(this, cacheKey);
                if (notUseCache)
                {
                    DataAccess.Libs.ClearCache(cacheKey);
                }
                databases.tmpDS.stockCodeDataTable codeTbl = null;
                obj = DataAccess.Libs.GetCache(cacheKey);
                if (obj != null)
                {
                    codeTbl = (obj as databases.tmpDS.stockCodeDataTable);
                }
                else
                {
                    codeTbl = DataAccess.Libs.GetStock_InPortfolio(porfolioList);
                    DataAccess.Libs.AddCache(cacheKey, codeTbl);
                }
                for (int idx = 0; idx < this.myStockTbl.Count; idx++)
                {
                    this.myStockTbl[idx].selected = (codeTbl.FindBycode(this.myStockTbl[idx].code) != null ? 1 : 0);
                }
                stockSource.Filter = this.myStockTbl.selectedColumn + "=1";
                break;
            }
        }
Beispiel #57
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.Normal, "RegFree processing {0}",
                           Path.GetFileName(Executable));

            StringCollection dllPaths = GetFilesFrom(Dlls);

            if (dllPaths.Count == 0)
            {
                string ext = Path.GetExtension(Executable);
                if (ext != null && ext.Equals(".dll", StringComparison.InvariantCultureIgnoreCase))
                {
                    dllPaths.Add(Executable);
                }
            }
            string manifestFile = string.IsNullOrEmpty(Output) ? Executable + ".manifest" : Output;

            try
            {
                var doc = new XmlDocument {
                    PreserveWhitespace = true
                };

                using (XmlReader reader = new XmlTextReader(manifestFile))
                {
                    if (reader.MoveToElement())
                    {
                        doc.ReadNode(reader);
                    }
                }

                // Register all DLLs temporarily
                using (var regHelper = new RegHelper(Log, Platform))
                {
                    regHelper.RedirectRegistry(!UserIsAdmin);
                    var creator       = new RegFreeCreator(doc, Log);
                    var filesToRemove = dllPaths.Cast <string>().Where(fileName => !File.Exists(fileName)).ToList();
                    foreach (var file in filesToRemove)
                    {
                        dllPaths.Remove(file);
                    }

                    foreach (string fileName in dllPaths)
                    {
                        Log.LogMessage(MessageImportance.Low, "\tRegistering library {0}", Path.GetFileName(fileName));
                        try
                        {
                            regHelper.Register(fileName, true, false);
                        }
                        catch (Exception e)
                        {
                            Log.LogMessage(MessageImportance.High, "Failed to register library {0}", fileName);
                            Log.LogMessage(MessageImportance.High, e.StackTrace);
                        }
                    }

                    string assemblyName = Path.GetFileNameWithoutExtension(manifestFile);
                    Debug.Assert(assemblyName != null);
                    // The C++ test programs won't run if an assemblyIdentity element exists.
                    //if (assemblyName.StartsWith("test"))
                    //	assemblyName = null;
                    string assemblyVersion = null;
                    try
                    {
                        assemblyVersion = FileVersionInfo.GetVersionInfo(Executable).FileVersion;
                    }
                    catch
                    {
                        // just ignore
                    }
                    if (string.IsNullOrEmpty(assemblyVersion))
                    {
                        assemblyVersion = "1.0.0.0";
                    }
                    XmlElement root = creator.CreateExeInfo(assemblyName, assemblyVersion, Platform);
                    foreach (string fileName in dllPaths)
                    {
                        if (NoTypeLib.Count(f => f.ItemSpec == fileName) != 0)
                        {
                            continue;
                        }

                        Log.LogMessage(MessageImportance.Low, "\tProcessing library {0}", Path.GetFileName(fileName));
                        creator.ProcessTypeLibrary(root, fileName);
                    }
                    creator.ProcessClasses(root);
                    creator.ProcessInterfaces(root);
                    foreach (string fragmentName in GetFilesFrom(Fragments))
                    {
                        Log.LogMessage(MessageImportance.Low, "\tAdding fragment {0}", Path.GetFileName(fragmentName));
                        creator.AddFragment(root, fragmentName);
                    }

                    foreach (string fragmentName in GetFilesFrom(AsIs))
                    {
                        Log.LogMessage(MessageImportance.Low, "\tAdding as-is fragment {0}", Path.GetFileName(fragmentName));
                        creator.AddAsIs(root, fragmentName);
                    }

                    foreach (string assemblyFileName in GetFilesFrom(DependentAssemblies))
                    {
                        Log.LogMessage(MessageImportance.Low, "\tAdding dependent assembly {0}", Path.GetFileName(assemblyFileName));
                        creator.AddDependentAssembly(root, assemblyFileName);
                    }

                    var settings = new XmlWriterSettings
                    {
                        OmitXmlDeclaration  = false,
                        NewLineOnAttributes = false,
                        NewLineChars        = Environment.NewLine,
                        Indent      = true,
                        IndentChars = "\t"
                    };
                    using (XmlWriter writer = XmlWriter.Create(manifestFile, settings))
                    {
                        doc.WriteContentTo(writer);
                    }

                    // Unregister DLLs
                    if (Unregister)
                    {
                        foreach (string fileName in dllPaths)
                        {
                            Log.LogMessage(MessageImportance.Low, "\tUnregistering library {0}",
                                           Path.GetFileName(fileName));
                            regHelper.Unregister(fileName, true);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e, true, true, null);
                return(false);
            }
            return(true);
        }
        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 = "";
                    }
                }
            }
        }
Beispiel #59
0
 public string Copy(string target, StringCollection items)
 {
     return(Paste(target, items, FileAction.Copy));
 }
Beispiel #60
0
        //public static bool IsComment(SiteInfo siteInfo, int channelId, string administratorName)
        //{
        //    return siteInfo.Additional.IsCommentable && AdminUtility.HasChannelPermissions(administratorName, siteInfo.Id, channelId, ConfigManager.Permissions.Channel.CommentCheck, ConfigManager.Permissions.Channel.CommentDelete);
        //}

        public static string GetColumnsHeadHtml(List<TableStyleInfo> tableStyleInfoArrayList, StringCollection attributesOfDisplay, SiteInfo siteInfo)
        {
            var builder = new StringBuilder();

            var arrayList = ContentUtility.GetColumnTableStyleInfoList(siteInfo, tableStyleInfoArrayList);
            foreach (var styleInfo in arrayList)
            {
                if (attributesOfDisplay.Contains(styleInfo.AttributeName))
                {
                    builder.Append(
                        $@"<th class=""text-nowrap"">{styleInfo.DisplayName}</th>");
                }
            }

            return builder.ToString();
        }