Search Results

Search found 7140 results on 286 pages for 'mike tostring'.

Page 20/286 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • Possible for C++ template to check for a function's existence?

    - by andy
    Is it possible to write a C++ template that changes behavior depending on if a certain member function is defined on a class? Here's a simple example of what I would want to write: template<class T> std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T->toString)) return obj->toString(); else return "toString not defined"; } So if class T has "toString" defined then it uses it, otherwise it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.

    Read the article

  • How do i convert from milliseconds to seconds units to be shown in a Label?

    - by Doron Muzar
    I have this code: private void Form1_MouseWheel(object sender, MouseEventArgs e) { if (leave == true) { if (e.Delta > 0) { if (timer1.Interval < 5000) { timer1.Interval += 1000; label2.Text = (timer1.Interval/1000).ToString(); } } else { if (timer1.Interval == 1000) { timer1.Interval -= 100; label2.Text = (timer1.Interval / 1000).ToString(); } } } } The original timer1 interval in the designer is set to 1000 milliseconds. In the mouse wheel event i did that it will show in the label2 the untis in seconds. And indeed when i move the mouse wheel up its slowing the timer and show it in seconds 1 2 3 4 5 The problem is with the second part i wanted that when its getting to 1 second or 1000 milliseconds if i will keep wheel it down it will show the units in 100 and change the timer1.interval in 100 units. So in label2 if it was on 1 second so now i will see 900 800 700 600 500 un till 100. And also the timer1 interval should be change to 900 milliseconds 800 700 600 untill 100. When its get to 100 just stop there dont keep getting under 100. The problem is with this part: if (timer1.Interval == 1000) { timer1.Interval -= 100; label2.Text = (timer1.Interval / 1000).ToString(); } Its not working at all. EDIT** My code now: if (leave == true) { if (e.Delta > 0) { if (timer1.Interval < 5000) { timer1.Interval += 1000; label2.Text = (timer1.Interval / 1000).ToString(); } } else { if (timer1.Interval > 1000) { timer1.Interval -= 1000; label2.Text = (timer1.Interval / 1000).ToString(); } else if (timer1.Interval <= 1000 && timer1.Interval > 100) { timer1.Interval -= 100; label2.Text = (timer1.Interval / (double)1000).ToString(); } } } But now if i was at 5 seconds(5000 milliseconds) now i move the wheel back down its counting 5 4 3 2 1 0 and stop on 0 It dosent show under 1 ...0.9 0.8 0.7 as it did before.

    Read the article

  • C++ Multiple Inheritance Question

    - by John
    The scenario generating this is quite complex so I'll strip out a few pieces and give an accurate representation of the classes involved. /* This is inherited using SI by many classes, as normal */ class IBase { virtual string toString()=0; }; /* Base2 can't inherit IBase due to other methods on IBase which aren't appropriate */ class Base2 { string toString() { ... } }; /* a special class, is this valid? */ class Class1 : public IBase, public Base2 { }; So, is this valid? Will there be conflicts on the toString? Or can Class1 use Base2::toString to satisfy IBase? Like I say there are lots of other things not shown, so suggestions for major design changes on this example are probably not that helpful... though any general suggestions/advice are welcome.

    Read the article

  • C#, wmi get disk manufacturer

    - by gloris
    Hi, how get USB flash(key) manufacturer name with C#? for example WD, Hama, Kingston... Now i with: "disk["Manufacturer"]", get: "Standard disk driver" string drive = "h"; ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\""); disk.Get(); Console.WriteLine(disk["VolumeSerialNumber"].ToString()); Console.WriteLine(disk["VolumeName"].ToString()); Console.WriteLine(disk["Manufacturer"].ToString());

    Read the article

  • Loading an XML file with todays date in the filename... need to fallback to old file if one with tod

    - by arala22
    So here is my question. Using javascript/jQuery I am currently loading in an XML file that has a file name such as carousel_large_2010-06-08.xml.. the way I am doing it is checked for todays date then grabbing a file that has that date in the filename... the issue is sometimes they wont be uploading a new file for a given day so it needs to fallback to a older date that exists.. Wondering how to do it? Here is my code: // set date for xml file var currentTime = new Date(), month = currentTime.getMonth() + 1, day = currentTime.getDate(), year = currentTime.getFullYear(); if(month.toString().length == 1){ month = '0'+month.toString(); } if(day.toString().length == 1){ day = '0'+day.toString(); } var dateObject = year+"-"+month+"-"+day; // start magic $jq.ajax({ type: "GET", url: "_xml/carousel/home/carousel_large_"+dateObject+".xml", dataType: "xml", success: HPCarousels.heroCarousel.parseXML, error: function(){ alert('Error Loading XML Content'); } });

    Read the article

  • How can i use listDictionary?

    - by Phsika
    i can fill my listdictinary but, if running error returns to me in " foreach (string ky in ld.Keys)"(invalid operation Exception was unhandled) Error Detail : After creating a pointer to the list of sample collection has been changed. C# ListDictionary ld = new ListDictionary(); foreach (DataColumn dc in dTable.Columns) { MessageBox.Show(dTable.Rows[0][dc].ToString()); ld.Add(dc.ColumnName, dTable.Rows[0][dc].ToString()); } foreach (string ky in ld.Keys) if (int.TryParse(ld[ky].ToString(), out QuantityInt)) ld[ky] = "integer"; else if(double.TryParse(ld[ky].ToString(), out QuantityDouble)) ld[ky]="double"; else ld[ky]="nvarchar";

    Read the article

  • to avoid page refresh during button click event in asp.net

    - by ush
    public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) // If page loads for first time { Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); // Assign the Session["update"] with unique value //=============== Page load code ========================= //============== End of Page load code =================== } } protected void Button1_Click(object sender, EventArgs e) { if (Session["update"].ToString() == ViewState["update"].ToString()) // If page not Refreshed { //=============== On click event code ========================= Label1.Text = TextBox1.Text; //lblDisplayAddedName.Text = txtName.Text; //=============== End of On click event code ================== // After the event/ method, again update the session Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); } else // If Page Refreshed { // Do nothing } } protected override void OnPreRender(EventArgs e) { ViewState["update"] = Session["update"]; } } this is not working for high resolution gradient background

    Read the article

  • Defining a select list through controller and view model

    - by Ibrar Hussain
    I have a View Model that looks like this: public class SomeViewModel { public SomeViewModel(IEnumerable<SelectListItem> orderTemplatesListItems) { OrderTemplateListItems = orderTemplatesListItems; } public IEnumerable<SelectListItem> OrderTemplateListItems { get; set; } } I then have an Action in my Controller that does this: public ActionResult Index() { var items = _repository.GetTemplates(); var selectList = items.Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }).ToList(); var viewModel = new SomeViewModel { OrderTemplateListItems = selectList }; return View(viewModel); } Lastly my view: @Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template") The code works fine and my select list populates wonderfully. Next thing I need to do is set the selected value that will come from a Session["orderTemplateId"] which is set when the user selects a particular option from the list. Now after looking online the fourth parameter should allow me to set a selected value, so if I do this: @Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text", 56), "Please select an order template") 56 is the Id of the item that I want selected, but to no avail. I then thought why not do it in the Controller? As a final attempt I tried building up my select list items in my Controller and then passing the items into the View: public ActionResult Index() { var items = _repository.GetTemplates(); var orderTemplatesList = new List<SelectListItem>(); foreach (var item in items) { if (Session["orderTemplateId"] != null) { if (item.Id.ToString() == Session["orderTemplateId"].ToString()) { orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = true }); } else { orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() }); } } else { orderTemplatesList.Add(new SelectListItem { Text = item.Name, Value = item.Id.ToString() }); } } var viewModel = new SomeViewModel { OrderTemplateListItems = orderTemplatesList }; return View(viewModel); } Leaving my View like so: @Html.DropDownListFor(n => n.OrderTemplateListItems, new SelectList(Model.OrderTemplateListItems, "value", "text"), "Please select an order template") Nothing! Why isn't this working for me?

    Read the article

  • Is this multi line if statement too complex?

    - by AndHeCodedIt
    I am validating input on a form and attempting to prompt the user of improper input(s) based on the combination of controls used. For example, I have 2 combo boxes and 3 text boxes. The 2 combo boxes must always have a value other than the first (default) value, but one of three, or two of three, or all text boxes can be filled to make the form valid. In one such scenario I have a 6 line if statement to try to make the test easily readable: if ((!String.Equals(ComboBoxA.SelectedValue.ToString(), DEFAULT_COMBO_A_CHOICE.ToString()) && !String.IsNullOrEmpty(TextBoxA.Text) && !String.Equals(ComboBoxB.SelectedValue.ToString(), DEFAULT_COMBO_B_CHOICE.ToString())) || (!String.IsNullOrEmpty(TextBoxB.Text) || !String.IsNullOrEmpty(TextBoxC.Text))) { //Do Some Validation } I have 2 questions: Should this type of if statement be avoided at all cost? Would it be better to enclose this test in another method? (This would be a good choice as this validation will happen in more than one scenario) Thanks for your input(s)!

    Read the article

  • Rewrite the foreach using lambda + C#3.0

    - by Newbie
    I am tryingv the following foreach (DataRow dr in dt.Rows) { if (dr["TABLE_NAME"].ToString().Contains(sheetName)) { tableName = dr["TABLE_NAME"].ToString(); } } by using lambda like string tableName = ""; DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i => { tableName = i["TABLE_NAME"].ToString().Contains(sheetName); } ); but getting compile time error "cannot implicitly bool to string". So how to achieve the same.? Thanks(C#3.0)

    Read the article

  • Is base method able to use derived base data members?

    - by iTayb
    Lets assume we have the following code: abstract class Base1 { protected int num; } class Der1:Base1 { protected Color color; protected string name; } class Der2:Base1 { protected DateTime dthen; } and so on. An array of base1 type exists and includes many objects created out of classes that are derived from base1. Is it possible to define the toString() method in the base class only? something like: public override string toString() { if (this is Der1) return "num = " + this.num + "color = " + this.color.toString() + " name = " this.name; if (this is Der2) return "num = " + this.num + "dthen = " + this.dthen.toString(); // and so on ... } Thank you very much :) P.S. This is not an homework question. I've just wondered about.

    Read the article

  • How to replace a codebehind method with an aspx method using ternary operator

    - by user466663
    I have an asp:hyperlink control as part of a gridview template. The code in the aspx page is given below: asp:HyperLink runat="server" ID="lnkEdit" ToolTip="Edit article" NavigateUrl='<%# GetUrl(Eval("ID").ToString(), Eval("CategoryID").ToString()) %' ImageUrl="~/Images/Edit.gif" The NavigateUrl value is obtained from the codebehind method GetUrl(string, string). The code works fine and is as follows: protected string GetUrl(string id, string categoryID) { var CategoryID = string.Empty; if (!String.IsNullOrEmpty(Request.QueryString["CatID"])) { CategoryID = Request.QueryString["CatID"].ToString(); } else if (!String.IsNullOrEmpty(categoryID)) { CategoryID = categoryID; } return "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + id + "&CatID=" + CategoryID; } I want to replace the code behind method by using a ternary operator within the aspx page. I tried something like below, but didn't work: asp:HyperLink runat="server" ID="lnkEdit" ToolTip="Edit article" NavigateUrl='<%# "~/TBSArticles/WriteOrEditArticle.aspx?ID=" + Eval("ID") + "&CatID=" + Eval(this.Request.QueryString["CatID"].ToString()) != ""? this.Request.QueryString["CatID"] : Eval("CategoryID")) %' ImageUrl="~/Images/Edit.gif" Any help will be greatly appreciated. Thanks

    Read the article

  • how to add a variables which comes from dataset in for loop Collection array in c#?

    - by leventkalay1986
    I have a collection of RSS items protected Collection<Rss.Items> list = new Collection<Rss.Items>(); The class RSS.Items includes properties such as Link, Text, Description, etc. But when I try to read the XML and set these properties: for (int i = 0; i < dt.Rows.Count; i++) { row = dt.Rows[i]; list[i].Link.Equals(row[0].ToString()); list[i].Description.Equals( row[1].ToString()); list[i].Title.Equals( row[2].ToString()); list[i].Date.Equals( Convert.ToDateTime(row[3])); } I get a null reference exception on the line list[i].Link.Equals(row[0].ToString()); What am I doing wrong?

    Read the article

  • String / DateTime Conversion problem (asp.net vb)

    - by Phil
    I have this code: Dim birthdaystring As String = MonthBirth.SelectedValue.ToString & "/" & DayBirth.SelectedValue.ToString & "/" & YearBirth.SelectedValue.ToString Dim birthday As DateTime = Convert.ToDateTime(birthdaystring) Which produces errors (String was not recognized as a valid DateTime.) The string was "01/31/1963". Any assistance would be appreciated. Thanks.

    Read the article

  • Add columnname and data from datatable to a dictionary? C#

    - by Nick
    Hi, I am looping through a datatable and currently I do string customerId = row["CustomerId"].ToString(); string companyName = row["Company Name"].ToString(); Instead of declaring every variable how do I add these do a dictionary? I was thinking something like: foreach (DataRow row in customerTbl.Rows) { Dictionary<string, string> customerDictionary = new Dictionary<string, string>(); customerDictionary.Add(row[].ToString(), row[].ToString()); so yeah, how do I get the row name and value into there? Thanks in advance.

    Read the article

  • Win32_Product InstallLocation (error)

    - by andrew
    in C#, i'm trying to get some properties from the instances of Win32_Product, but i seem to have an error saying "Object reference not set to an instance of an object." here's the code: class Package { public string productName; public string installDate; public string installLocation; } class InstalledPackages { public static List<Package> get() { List<Package> packages = new List<Package>(); string query = "SELECT * FROM Win32_Product"; ManagementScope oMs = new ManagementScope(); ObjectQuery oQuery = new ObjectQuery(query); ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery); ManagementObjectCollection installedPackages = oSearcher.Get(); foreach (ManagementObject package in installedPackages) { Package p = new Package(); p.productName = package["Name"].ToString(); p.installLocation = package["InstallLocation"].ToString(); p.installDate = package["InstallDate"].ToString(); packages.Add(p); } return packages; } } the exception appears when it gets to p.installLocation = package["InstallLocation"].ToString(); also, i get one if i try to do p.installLocation = package["InstallDate2"].ToString(); if i'm asking for InstallDate it works. (i'm using Windows 7 Ultimate x64)

    Read the article

  • Add Method to Built In Class

    - by Evorlor
    I am pretty sure this is not doable, but I will go ahead and cross my fingers and ask. I am trying to add a method to a built in class. I want this method to be callable by all of the built in class's subclasses. Specifically: I have a JButton, a JTextPane, and other JComponents. I want to be able to pass in a JDom Element instead of a Rectangle to setBounds(). My current solution is to extend each JComponent subclass with the desired methods, but that is a LOT of duplicate code. Is there a way I can write the following method just one time, and have it callable on all JComponent objects? Or is it required that I extend each subclass individually, and copy and paste the method below? public void setBounds(Element element) { this.setBounds(Integer.parseInt(element.getAttribute( "x").toString()), Integer.parseInt(element .getAttribute("y").toString()), Integer .parseInt(element.getAttribute("width").toString()), Integer.parseInt(element.getAttribute("height") .toString())); }

    Read the article

  • How can i solve "0 " value try to get length value?

    - by Phsika
    if i try to add int value into array with string length Whole data is "0" why? and how can solve it? for (int j = 0; j < dTable.Columns.Count; j++) for (int i = 0; i < dTable.Rows.Count; i++) { mycounter[i] = dTable.Rows[i][j].ToString().Length; } it is not related to mycounter because: string test = ""; foreach(DataColumn dc in dTable.Columns) for (int i = 0; i < dTable.Rows.Count; i++) { // MessageBox.Show(dTable.Rows[i][dc].ToString()); test = dTable.Rows[i][dc].ToString().Length.ToString(); }

    Read the article

  • Subtype polymorphism and arrays

    - by user133466
    Computer[] labComputers = new Computer[10]; with public class Computer { ... void toString(){ // print computer specs } } public class Notebook extends Computer{ ... void toString(){ // print computer specs + laptop color } } each subscripted variable labComputers[i] can reference either a Computer object or a Notebook object because Notebook is a subclass of Computer. For the method call labComputers[i].toString(), polymorphism ensures that the correct toString method is called. I wonder what if we do Notebook[] labComputers = new Notebook[10]; what kind or error would I get if I reference with Computer object and a Notebook object

    Read the article

  • c# xml function to check whether a string is equal to a xml attribute, to add selected combobox item

    - by fuch
    i want to check the combobox.selecteditem.tostring() on combobox select in a given xml with several nodes, where each one has an attribute called "name" private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { try { textBox1.AppendText(nameAttributeCheck(comboBox1.SelectedItem.ToString())); } catch { } } private string nameAttributeCheck(string a) { XmlDocument doc = new XmlDocument(); doc.Load("armor.xml"); XmlElement root = doc.DocumentElement; XmlNodeList items = root.SelectNodes("/items"); String result = null; try { foreach (XmlNode item in items) { if (string.Equals(a, item.Attributes["name"].InnerText.ToString())) { result += item.Attributes["picture"].InnerText.ToString(); } } } catch { } return result; } each time i try it, nothing happens

    Read the article

  • VB Change Calulator

    - by BlueBeast
    I am creating a VB 2008 change calculator as an assignment. The program is to use the amount paid - the amount due to calculate the total.(this is working fine). After that, it is to break that amount down into dollars, quarters, dimes, nickels, and pennies. The problem I am having is that sometimes the quantity of pennies, nickels or dimes will be a negative number. For example $2.99 = 3 Dollars and -1 Pennies. SOLVED Thanks to the responses, here is what I was able to make work with my limited knowledge. Option Explicit On Option Strict Off Option Infer Off Public Class frmMain Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click 'Clear boxes lblDollarsAmount.Text = String.Empty lblQuartersAmount.Text = String.Empty lblDimesAmount.Text = String.Empty lblNickelsAmount.Text = String.Empty lblPenniesAmount.Text = String.Empty txtOwed.Text = String.Empty txtPaid.Text = String.Empty lblAmountDue.Text = String.Empty txtOwed.Focus() End Sub Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click 'Close application' Me.Close() End Sub Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click ' Find Difference between Total Price and Total Received lblAmountDue.Text = Val(txtPaid.Text) - Val(txtOwed.Text) Dim intChangeAmount As Integer = lblAmountDue.Text * 100 'Declare Integers Dim intDollarsBack As Integer Dim intQuartersBack As Integer Dim intDimesBack As Integer Dim intNickelsBack As Integer Dim intPenniesBack As Integer ' Change Values Const intDollarValue As Integer = 100 Const intQuarterValue As Integer = 25 Const intDimeValue As Integer = 10 Const intNickelValue As Integer = 5 Const intPennyValue As Integer = 1 'Dollars intDollarsBack = CInt(Val(intChangeAmount \ intDollarValue)) intChangeAmount = intChangeAmount - Val(Val(intDollarsBack) * intDollarValue) lblDollarsAmount.Text = intDollarsBack.ToString 'Quarters intQuartersBack = CInt(Val(intChangeAmount \ intQuarterValue)) intChangeAmount = intChangeAmount - Val(Val(intQuartersBack) * intQuarterValue) lblQuartersAmount.Text = intQuartersBack.ToString 'Dimes intDimesBack = CInt(Val(intChangeAmount \ intDimeValue)) intChangeAmount = intChangeAmount - Val(Val(intDimesBack) * intDimeValue) lblDimesAmount.Text = intDimesBack.ToString 'Nickels intNickelsBack = CInt(Val(intChangeAmount \ intNickelValue)) intChangeAmount = intChangeAmount - Val(Val(intNickelsBack) * intNickelValue) lblNickelsAmount.Text = intNickelsBack.ToString 'Pennies intPenniesBack = CInt(Val(intChangeAmount \ intPennyValue)) intChangeAmount = intChangeAmount - Val(Val(intPenniesBack) * intPennyValue) lblPenniesAmount.Text = intPenniesBack.ToString End Sub End Class

    Read the article

  • display data from tables that contain a null value

    - by user2631662
    I need the code below to say - if myReader reads a null entry a new method is called. At the moment it will not display data from tables that contain a null value conDataBase.Open(); myReader = cmdDataBase.ExecuteReader(); while (myReader.Read()) { if (myReader["Code_CodeID"] != DBNull.Value) { string sFirst = myReader["First"].ToString(); string sLast = myReader["Last"].ToString(); string sAdd1 = myReader["Address1"].ToString(); string sCode = myReader["Code"].ToString(); txtFirst.Text = sFirst; txtSecond.Text = sLast; txtadd1.Text = sAdd1; txtDeviceIMEI.Text = sCode; } } } else { //go to a new method } }

    Read the article

  • Automatically create bug resolution task using the TFS 2010 API

    - by Bob Hardister
    My customer requires bug resolution to be approved and tracked.  To minimize the overhead for developers I implemented a TFS 2010 server-side plug-in to automatically create a child resolution task for the bug when the “CCB” field is set to approved. The CCB field is a custom field.  I also added the story points field to the bug WIT for sizing purposes. Redundant tasks will not be created unless the bug title is changed or the prior task is closed. The program writes an audit trail to a log file visible in the TFS Admin Console Log view. Here’s the code. BugAutoTask.cs /* SPECIFICATION * When the CCB field on the bug is set to approved, create a child task where the task: * name = Resolve bug [ID] - [Title of bug] * assigned to = same as assigned to field on the bug * same area path * same iteration path * activity = Bug Resolution * original estimate = bug points * * The source code is used to build a dll (Ows.TeamFoundation.BugAutoTaskCreation.PlugIns.dll), * which needs to be copied to * C:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins * on ALL TFS application-tier servers. * * Author: Bob Hardister. */ using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Text; using System.Diagnostics; using System.Linq; using Microsoft.TeamFoundation.Common; using Microsoft.TeamFoundation.Framework.Server; using Microsoft.TeamFoundation.WorkItemTracking.Client; using Microsoft.TeamFoundation.WorkItemTracking.Server; using Microsoft.TeamFoundation.Client; using System.Collections; namespace BugAutoTaskCreation { public class BugAutoTask : ISubscriber { public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType, object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties) { statusCode = 0; properties = null; statusMessage = String.Empty; // Error message for for tracing last code executed and optional fields string lastStep = "No field values found or set "; try { if ((notificationType == NotificationType.Notification) && (notificationEventArgs.GetType() == typeof(WorkItemChangedEvent))) { WorkItemChangedEvent workItemChange = (WorkItemChangedEvent)notificationEventArgs; // see ConnectToTFS() method below to select which TFS instance/collection // to connect to TfsTeamProjectCollection tfs = ConnectToTFS(); WorkItemStore wiStore = tfs.GetService<WorkItemStore>(); lastStep = lastStep + ": connection to TFS successful "; // Get the work item that was just changed by the user. WorkItem witem = wiStore.GetWorkItem(workItemChange.CoreFields.IntegerFields[0].NewValue); lastStep = lastStep + ": retrieved changed work item, ID:" + witem.Id + " "; // Filter for Bug work items only if (witem.Type.Name == "Bug") { // DEBUG lastStep = lastStep + ": changed work item is a bug "; // Filter for CCB (i.e. Baseline Status) field set to approved only bool BaselineStatusChange = false; if (workItemChange.ChangedFields != null) { ProcessBugRevision(ref lastStep, workItemChange, wiStore, ref witem, ref BaselineStatusChange); } } } } catch (Exception e) { Trace.WriteLine(e.Message); Logger log = new Logger(); log.WriteLineToLog(MsgLevel.Error, "Application error: " + lastStep + " - " + e.Message + " - " + e.InnerException); } statusCode = 1; statusMessage = "Bug Auto Task Evaluation Completed"; properties = null; return EventNotificationStatus.ActionApproved; } // PRIVATE METHODS private static void ProcessBugRevision(ref string lastStep, WorkItemChangedEvent workItemChange, WorkItemStore wiStore, ref WorkItem witem, ref bool BaselineStatusChange) { foreach (StringField field in workItemChange.ChangedFields.StringFields) { // DEBUG lastStep = lastStep + ": last changed field is - " + field.Name + " "; if (field.Name == "Baseline Status") { lastStep = lastStep + ": retrieved bug baseline status field value, bug ID:" + witem.Id + " "; BaselineStatusChange = (field.NewValue != field.OldValue); if ((BaselineStatusChange) && (field.NewValue == "Approved")) { // Instanciate logger Logger log = new Logger(); // *** Create resolution task for this bug *** // ******************************************* // Get the team project and selected field values of the bug work item Project teamProject = witem.Project; int bugID = witem.Id; string bugTitle = witem.Fields["System.Title"].Value.ToString(); string bugAssignedTo = witem.Fields["System.AssignedTo"].Value.ToString(); string bugAreaPath = witem.Fields["System.AreaPath"].Value.ToString(); string bugIterationPath = witem.Fields["System.IterationPath"].Value.ToString(); string bugChangedBy = witem.Fields["System.ChangedBy"].OriginalValue.ToString(); string bugTeamProject = witem.Project.Name; lastStep = lastStep + ": all mandatory bug field values found "; // Optional fields Field bugPoints = witem.Fields["Microsoft.VSTS.Scheduling.StoryPoints"]; if (bugPoints.Value != null) { lastStep = lastStep + ": all mandatory and optional bug field values found "; } // Initialize child resolution task title string childTaskTitle = "Resolve bug " + bugID + " - " + bugTitle; // At this point I can check if a resolution task (of the same name) // for the bug already exist // If so, do not create a new resolution task bool createResolutionTask = true; WorkItem parentBug = wiStore.GetWorkItem(bugID); WorkItemLinkCollection links = parentBug.WorkItemLinks; foreach (WorkItemLink wil in links) { if (wil.LinkTypeEnd.Name == "Child") { WorkItem childTask = wiStore.GetWorkItem(wil.TargetId); if ((childTask.Title == childTaskTitle) && (childTask.State != "Closed")) { createResolutionTask = false; log.WriteLineToLog(MsgLevel.Info, "Team project " + bugTeamProject + ": " + bugChangedBy + " - set the CCB field to \"Approved\" for bug, ID: " + bugID + ". Task not created as open one of the same name already exist, ID:" + childTask.Id); } } } if (createResolutionTask) { // Define the work item type of the new work item WorkItemTypeCollection workItemTypes = wiStore.Projects[teamProject.Name].WorkItemTypes; WorkItemType wiType = workItemTypes["Task"]; // Setup the new task and assign field values witem = new WorkItem(wiType); witem.Fields["System.Title"].Value = "Resolve bug " + bugID + " - " + bugTitle; witem.Fields["System.AssignedTo"].Value = bugAssignedTo; witem.Fields["System.AreaPath"].Value = bugAreaPath; witem.Fields["System.IterationPath"].Value = bugIterationPath; witem.Fields["Microsoft.VSTS.Common.Activity"].Value = "Bug Resolution"; lastStep = lastStep + ": all mandatory task field values set "; // Optional fields if (bugPoints.Value != null) { witem.Fields["Microsoft.VSTS.Scheduling.OriginalEstimate"].Value = bugPoints.Value; lastStep = lastStep + ": all mandatory and optional task field values set "; } // Check for validation errors before saving the new task and linking it to the bug ArrayList validationErrors = witem.Validate(); if (validationErrors.Count == 0) { witem.Save(); // Link the new task (child) to the bug (parent) var linkType = wiStore.WorkItemLinkTypes[CoreLinkTypeReferenceNames.Hierarchy]; // Fetch the work items to be linked var parentWorkItem = wiStore.GetWorkItem(bugID); int taskID = witem.Id; var childWorkItem = wiStore.GetWorkItem(taskID); // Add a new link to the parent relating the child and save it parentWorkItem.Links.Add(new WorkItemLink(linkType.ForwardEnd, childWorkItem.Id)); parentWorkItem.Save(); log.WriteLineToLog(MsgLevel.Info, "Team project " + bugTeamProject + ": " + bugChangedBy + " - set the CCB field to \"Approved\" for bug, ID:" + bugID + ", which automatically created child resolution task, ID:" + taskID); } else { log.WriteLineToLog(MsgLevel.Error, "Error in creating bug resolution child task for bug ID:" + bugID); foreach (Field taskField in validationErrors) { log.WriteLineToLog(MsgLevel.Error, " - Validation Error in task field: " + taskField.ReferenceName); } } } } } } } private TfsTeamProjectCollection ConnectToTFS() { // Connect to TFS string tfsUri = string.Empty; // Production TFS instance production collection tfsUri = @"xxxx"; // Production TFS instance admin collection //tfsUri = @"xxxxx"; // Local TFS testing instance default collection //tfsUri = @"xxxxx"; TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new System.Uri(tfsUri)); tfs.EnsureAuthenticated(); return tfs; } // HELPERS public string Name { get { return "Bug Auto Task Creation Event Handler"; } } public SubscriberPriority Priority { get { return SubscriberPriority.Normal; } } public enum MsgLevel { Info, Warning, Error }; public Type[] SubscribedTypes() { return new Type[1] { typeof(WorkItemChangedEvent) }; } } } Logger.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace BugAutoTaskCreation { class Logger { // fields private string _ApplicationDirectory = @"C:\ProgramData\Microsoft\Team Foundation\Server Configuration\Logs"; private string _LogFileName = @"\CFG_ACCT_AT_OWS_BugAutoTaskCreation.log"; private string _LogFile; private string _LogTimestamp = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"); private string _MsgLevelText = string.Empty; // default constructor public Logger() { // check for a prior log file FileInfo logFile = new FileInfo(_ApplicationDirectory + _LogFileName); if (!logFile.Exists) { CreateNewLogFile(ref logFile); } } // properties public string ApplicationDirectory { get { return _ApplicationDirectory; } set { _ApplicationDirectory = value; } } public string LogFile { get { _LogFile = _ApplicationDirectory + _LogFileName; return _LogFile; } set { _LogFile = value; } } // PUBLIC METHODS public void WriteLineToLog(BugAutoTask.MsgLevel msgLevel, string logRecord) { try { // set msgLevel text if (msgLevel == BugAutoTask.MsgLevel.Info) { _MsgLevelText = "[Info @" + MsgTimeStamp() + "] "; } else if (msgLevel == BugAutoTask.MsgLevel.Warning) { _MsgLevelText = "[Warning @" + MsgTimeStamp() + "] "; } else if (msgLevel == BugAutoTask.MsgLevel.Error) { _MsgLevelText = "[Error @" + MsgTimeStamp() + "] "; } else { _MsgLevelText = "[Error: unsupported message level @" + MsgTimeStamp() + "] "; } // write a line to the log file StreamWriter logFile = new StreamWriter(_ApplicationDirectory + _LogFileName, true); logFile.WriteLine(_MsgLevelText + logRecord); logFile.Close(); } catch (Exception) { throw; } } // PRIVATE METHODS private void CreateNewLogFile(ref FileInfo logFile) { try { string logFilePath = logFile.FullName; // write the log file header _MsgLevelText = "[Info @" + MsgTimeStamp() + "] "; string cpu = string.Empty; if (Environment.Is64BitOperatingSystem) { cpu = " (x64)"; } StreamWriter newLog = new StreamWriter(logFilePath, false); newLog.Flush(); newLog.WriteLine(_MsgLevelText + "===================================================================="); newLog.WriteLine(_MsgLevelText + "Team Foundation Server Administration Log"); newLog.WriteLine(_MsgLevelText + "Version : " + "1.0.0 Author: Bob Hardister"); newLog.WriteLine(_MsgLevelText + "DateTime : " + _LogTimestamp); newLog.WriteLine(_MsgLevelText + "Type : " + "OWS Custom TFS API Plug-in"); newLog.WriteLine(_MsgLevelText + "Activity : " + "Bug Auto Task Creation for CCB Approved Bugs"); newLog.WriteLine(_MsgLevelText + "Area : " + "Build Explorer"); newLog.WriteLine(_MsgLevelText + "Assembly : " + "Ows.TeamFoundation.BugAutoTaskCreation.PlugIns.dll"); newLog.WriteLine(_MsgLevelText + "Location : " + @"C:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins"); newLog.WriteLine(_MsgLevelText + "User : " + Environment.UserDomainName + @"\" + Environment.UserName); newLog.WriteLine(_MsgLevelText + "Machine : " + Environment.MachineName); newLog.WriteLine(_MsgLevelText + "System : " + Environment.OSVersion + cpu); newLog.WriteLine(_MsgLevelText + "===================================================================="); newLog.WriteLine(_MsgLevelText); newLog.Close(); } catch (Exception) { throw; } } private string MsgTimeStamp() { string msgTimestamp = string.Empty; return msgTimestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); } } }

    Read the article

  • How to insert a word into a string in Perl

    - by Nano HE
    #!C:\Perl\bin\perl.exe use strict; use warnings; use Data::Dumper; my $fh = \*DATA; while(my $line = <$fh>) { $line =~ s/ ^/male /x ; print $line ; } __DATA__ 1 0104 Mike Lee 2:01:48 output male 1 0104 Mike Lee 2:01:48 Then I tried to insert male after the racenumber(0104), I replaced the code with style. $line =~ s/ ^\d+\s+\d+\s+ /male /x ; # but failed Acturally I want the output. thank you. 1 0104 male Mike Lee 2:01:48

    Read the article

  • How do I insert a word into a string in Perl?

    - by Nano HE
    #!C:\Perl\bin\perl.exe use strict; use warnings; use Data::Dumper; my $fh = \*DATA; while(my $line = <$fh>) { $line =~ s/ ^/male /x ; print $line ; } __DATA__ 1 0104 Mike Lee 2:01:48 output male 1 0104 Mike Lee 2:01:48 Then I tried to insert male after the racenumber(0104), I replaced the code with style. $line =~ s/ ^\d+\s+\d+\s+ /male /x ; # but failed Acturally I want the output. thank you. 1 0104 male Mike Lee 2:01:48

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >