I have a program which connects to a site and gets the list of orders using soap api. But i have a really strange issue. When a i try to get the orders of a day which there is no orders and then try get list of orders of a day i get this error. But strange thing is if a put a break point to line where i got the error and evalute the program step by step i don't get any errors. How could that happen. herre is the code.
https://api.n11.com/ws/OrderService.wsdl
using n11.Deneme.Forms.com.n11.api;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace n11.Deneme.Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strStartDate = "18/01/2020";
string strEndDate = "18/01/2020";
long totalCountValue = 50;
int currentPageValue = 0;
int pageCountValue = 1;
int pageSizeValue = 50;
Authentication auth = new Authentication();
auth.appKey = "b891a6b9-cb97-4a7e-9ffb-f7b1e2a593e8";
auth.appSecret = "pHCjYYadxwTG64Ej";
OrderSearchPeriod orderSearchPeriod = new OrderSearchPeriod();
orderSearchPeriod.startDate = strStartDate;
orderSearchPeriod.endDate = strEndDate;
OrderDataListRequest orderDataListRequest = new OrderDataListRequest();
//orderDataListRequest.status = "1";
orderDataListRequest.period = orderSearchPeriod;
//orderDataListRequest.orderNumber = "209524598478";
PagingData pagingData = new PagingData();
pagingData.currentPage = currentPageValue;
pagingData.pageCount = pageCountValue;
pagingData.pageSize = pageSizeValue;
pagingData.totalCount = totalCountValue;
DetailedOrderListRequest request = new DetailedOrderListRequest();
request.auth = auth;
request.pagingData = pagingData;
request.searchData = orderDataListRequest;
OrderServicePortService port = new OrderServicePortService();
DetailedOrderListResponse response = port.DetailedOrderList(request);
List<DetailedOrderData> orderList = response.orderList.ToList();
foreach (var order in orderList)
{
MessageBox.Show(order.totalAmount.ToString() + " - " + order.orderNumber + " - " + order.citizenshipId + " - " + order.createDate);
long orderIdValue = order.id;
OrderDataRequest orderDataRequest = new OrderDataRequest();
orderDataRequest.id = orderIdValue;
OrderDetailRequest orderdetailrequest = new OrderDetailRequest();
orderdetailrequest.auth = auth;
orderdetailrequest.orderRequest = orderDataRequest;
OrderServicePortService port1 = new OrderServicePortService();
OrderDetailResponse orderDetailResponse = port1.OrderDetail(orderdetailrequest);
OrderDetailData orderDetail = orderDetailResponse.orderDetail;
MessageBox.Show(orderDetail.orderNumber);
List<OrderSearchData> orderItemList = orderDetail.itemList.ToList();
foreach (var item in orderItemList)
{
MessageBox.Show(item.shipmentInfo.campaignNumber);
}
}
}
}
}
If you're getting the error on the line:
List<DetailedOrderData> orderList = response.orderList.ToList(); //I GOT THE ERROR ON THIS LINE
then the thing to do is to look at how response.orderList gets a value. In particular, does it do something with threads, tasks, timers, external events, or anything else like that - which could mean that it gets populated shortly after the initial return from DetailedOrderList, which could explain why it works when you debug and step through (adding a crucial delay into things).
You could also simply do:
var tmp = response.orderList;
if (tmp == null) throw new InvalidOperationException(
"hey, response.orderList was null! this is not good!");
List<DetailedOrderData> orderList = tmp.ToList();
return orderList;
which would make it very clear and explicit that this is what is happening. If you don't get this exception, but something else, then: more debugging needed!
if(response.orderList == null)
{
var temp = button1_Click.PerformClick();
return temp;
}
else
{
List<DetailedOrderData> orderList = response.orderList.ToList();
return orderList;
}
Related
I am making a unity game and have one strange situation, which I will try to explain.
Here is my UserCreator class in which I want to return nativeCountry from another class (MySQLCountryManager):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class UserCreator : MonoBehaviour
{
public static PersonModel CreateUser(PersonModel model)
{
CountryModel nativeCountry = new CountryModel();
nativeCountry = MySQLCountryManager.GetCountryByName(model.NativeCountry);
<some other code here....>
}
}
And here is MySQLCountryManager class with GetCountryByName method:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class MySQLCountryManager : MonoBehaviour
{
public static CountryModel GetCountryByName(string countryName)
{
CountryModel country = new CountryModel();
WWWForm form = new WWWForm();
form.AddField("CountryName", countryName);
UnityWebRequestAsyncOperation getCountryByName = new UnityWebRequestAsyncOperation();
getCountryByName = UnityWebRequest.Post(WebReguests.getCountryByName, form).SendWebRequest();
List<string> results = new List<string>();
if (getCountryByName.webRequest.isNetworkError || getCountryByName.webRequest.isHttpError)
{
Debug.LogError(getCountryByName.webRequest.error);
}
else
{
var data = getCountryByName.webRequest.downloadHandler.text;
string[] result = data.Split(',');
for (int i = 0; i < result.Length; i++)
{
results.Add(result[i]);
}
int id;
bool idOk;
idOk = int.TryParse(results[0], out id );
if (idOk)
{
country.id = id;
}
country.CountryName = results[1];
byte[] flagBytes = Convert.FromBase64String(results[2]);
country.Flag = flagBytes;
byte[] shapeBytes = Convert.FromBase64String(results[3]);
country.Shape = shapeBytes;
byte[] woP = Convert.FromBase64String(results[4]);
country.WorldPosition = woP;
byte[] coa = Convert.FromBase64String(results[5]);
country.CoatOfArms = coa;
byte[] dishPicBytes = Convert.FromBase64String(results[6]);
country.DishPic = dishPicBytes;
byte[] curiosityBytes = Convert.FromBase64String(results[7]);
country.CuriosityPic = curiosityBytes;
country.Continent = results[8];
country.Population = results[9];
country.Capital = results[10];
country.Language = results[11];
country.Currency = results[12];
country.Religion = results[13];
country.DishName = results[14];
}
return country;
}
Now, the problem is, when I start debugging project in Visual Studio 2019 if I go Step Into on native country in UserCreator and then Step Into in MySQLCountryManager.GetCountryById, code works fine and returns nativeCountry as I expect. But when I go Step Over nativeCountry, it always throws some exceptions, like 'Index was out of range', 'Input string is not in a correct format' etc. And this is happening for all methods with UnityWebRequest called from UserCreator class.
I tried to google for this but nothing useful was found.
Any idea why this is happening?
tl;dr: Sounds like a race condition to me!
While stepping into the method you most probably give the asynchronous request just enough time to actually finish in the background.
I don't see where you are waiting for the results of the asynchronous download.
See the examples of UnityWebRequest.Post => as with any other asynchronous execution you have to wait until the results are actually back.
Usually you would use a Coroutine with callback like e.g.
public static void GetCountryByNameAsync(MonoBehaviour caller, string countryName, Action<CountryModel> whenDone)
{
caller.StartCoroutine(GetCountryByNameRoutine(countryName, whenDone))
}
private static IEnumerator GetCountryByNameRoutine(string countryName, Action<CountryModel> whenDone)
{
var form = new WWWForm();
form.AddField("CountryName", countryName);
using(var request = UnityWebRequest.Post(WebReguests.getCountryByName, form))
{
// WAIT until the request has either failed or succeeded
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
yield break;
}
var data = request.downloadHandler.text;
var results = data.Split(',');
var country = new CountryModel();
if (int.TryParse(results[0], out var id))
{
country.id = id;
}
country.CountryName = results[1];
var flagBytes = Convert.FromBase64String(results[2]);
country.Flag = flagBytes;
var shapeBytes = Convert.FromBase64String(results[3]);
country.Shape = shapeBytes;
var woP = Convert.FromBase64String(results[4]);
country.WorldPosition = woP;
var coa = Convert.FromBase64String(results[5]);
country.CoatOfArms = coa;
var dishPicBytes = Convert.FromBase64String(results[6]);
country.DishPic = dishPicBytes;
var curiosityBytes = Convert.FromBase64String(results[7]);
country.CuriosityPic = curiosityBytes;
country.Continent = results[8];
country.Population = results[9];
country.Capital = results[10];
country.Language = results[11];
country.Currency = results[12];
country.Religion = results[13];
country.DishName = results[14];
whenDone?.Invoke(country);
}
}
then later you would rather use it like e.g.
// caller will be whatever script is actually calling this method
// we will take that reference to make it also responsible for executing the according Coroutine
public static void CreateUserAsync(MonoBehaviour caller, PersonModel model, Action<PersonModel> whenDone)
{
MySQLCountryManager.GetCountryByName(caller, model.NativeCountry, nativeCountry =>
{
<some other code here....>
whenDone?.Invoke(theCreatedPersonModel);
});
}
Or if it gets more complex instead of Coroutines you might rather use an async - await approach and pass the final result back into the Unity main thread.
Hello everyone I want to ask about how can list ports and mac addresses of devices connected to switch using C#.
I have found code which works for Dell switch. I need it for Cisco switch
using SnmpSharpNet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace PortMapper
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
List<KeyValuePair<string, string>> portList = new List<KeyValuePair<string, string>>();
List<Portmap> portMaps = new List<Portmap>();
public class Portmap
{
public string Hostname { get; set; }
public string Port { get; set; }
public string IP { get; set; }
public string MAC { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
IPAddress ip = IPAddress.Parse("192.168.0.2");
IPAddress ip2 = IPAddress.Parse("192.168.0.3");
SnmpWalk(ip, "community", "1.3.6.1.2.1.17.7.1.2.2.1.2.1", "1");
SnmpWalk(ip2, "community","1.3.6.1.2.1.17.7.1.2.2.1.2.1", "2");
DhcpQuery("netsh", "dhcp server \\\\servername scope 192.168.0.0 show clients", "192");
List<Portmap> gridResults = new List<Portmap>();
//Example of filtering uplink ports from other switches
foreach(Portmap portMap in portMaps)
{
if (portMap.Port != "1/2/48" && portMap.Port != "2/1/48")
{
gridResults.Add(portMap);
}
}
PortMapGrid.ItemsSource = gridResults;
}
//Use NETSH to retrieve a list of DHCP MAC and IP addresses
private void DhcpQuery(string cmd, string args, string subnet)
{
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.FileName = cmd;
procStartInfo.Arguments = args;
procStartInfo.CreateNoWindow = true;
string output;
using (Process proc = Process.Start(procStartInfo))
{
output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
}
//Find valid leases in command output
string[] lines = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
List<string> leases = new List<string>();
foreach (string line in lines)
{
if (line.StartsWith(subnet))
{
leases.Add(line);
}
}
//Create threads
Thread[] threadArray = new Thread[leases.Count];
int threadcount = 0;
//Loop each Dhcp Lease
foreach (string line in leases)
{
string[] pieces = line.Split('-');
string ipAddress = pieces[0].Trim();
string mac = "";
string hostname = "";
foreach (string piece in pieces)
{
if (piece.Trim().Length == 2)
{
mac += piece;
}
}
ThreadStart start = delegate
{
hostname = GetHost(ipAddress);
foreach (KeyValuePair<string, string> port in portList)
{
if (port.Key.ToUpper().Trim() == mac.ToUpper().Trim())
{
Portmap portMap = new Portmap();
portMap.IP = ipAddress;
portMap.MAC = mac.ToUpper();
portMap.Port = port.Value;
portMap.Hostname = hostname;
portMaps.Add(portMap);
}
}
};
threadArray[threadcount] = new Thread(start);
threadArray[threadcount].Start();
threadcount = threadcount + 1;
}
//Join all threads in the array to wait for results
for (int i = 0; i < threadcount; i++)
{
threadArray[i].Join();
}
}
//SNMPWALK the ports on a switch or stack of switches. Ports will be labeled SwitchNum/Stack Number/Port Numbers.
private void SnmpWalk(IPAddress ip, string snmpCommunity, string oid, string switchNum)
{
UdpTarget target = new UdpTarget(ip);
// SNMP community name
OctetString community = new OctetString(snmpCommunity);
// Define agent parameters class
AgentParameters param = new AgentParameters(community);
// Set SNMP version to 1
param.Version = SnmpVersion.Ver1;
// Define Oid that is the root of the MIB tree you wish to retrieve
Oid rootOid = new Oid(oid);
// This Oid represents last Oid returned by the SNMP agent
Oid lastOid = (Oid)rootOid.Clone();
// Pdu class used for all requests
Pdu pdu = new Pdu(PduType.GetNext);
// Loop through results
while (lastOid != null)
{
// When Pdu class is first constructed, RequestId is set to a random value
// that needs to be incremented on subsequent requests made using the
// same instance of the Pdu class.
if (pdu.RequestId != 0)
{
pdu.RequestId += 1;
}
// Clear Oids from the Pdu class.
pdu.VbList.Clear();
// Initialize request PDU with the last retrieved Oid
pdu.VbList.Add(lastOid);
// Make SNMP request
SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
// You should catch exceptions in the Request if using in real application.
// If result is null then agent didn't reply or we couldn't parse the reply.
if (result != null)
{
// ErrorStatus other then 0 is an error returned by
// the Agent - see SnmpConstants for error definitions
if (result.Pdu.ErrorStatus != 0)
{
// agent reported an error with the request
Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
result.Pdu.ErrorStatus,
result.Pdu.ErrorIndex);
lastOid = null;
break;
}
else
{
// Walk through returned variable bindings
foreach (Vb v in result.Pdu.VbList)
{
// Check that retrieved Oid is "child" of the root OID
if (rootOid.IsRootOf(v.Oid))
{
//Convert OID to MAC
string[] macs = v.Oid.ToString().Split('.');
string mac = "";
int counter = 0;
foreach (string chunk in macs)
{
if (counter >= macs.Length - 6)
{
mac += string.Format("{0:X2}", int.Parse(chunk));
}
counter += 1;
}
//Assumes a 48 port switch (52 actual). You need to know these values to correctly iterate through a stack of switches.
int dellSwitch = 1 + int.Parse(v.Value.ToString()) / 52;
int port = int.Parse(v.Value.ToString()) - (52 * (dellSwitch - 1));
KeyValuePair<string, string> Port = new KeyValuePair<string, string>(mac, switchNum + "/" + dellSwitch.ToString() + "/" + port.ToString());
portList.Add(Port);
//Exit Loop
lastOid = v.Oid;
}
else
{
//End of the requested MIB tree. Set lastOid to null and exit loop
lastOid = null;
}
}
}
}
else
{
Console.WriteLine("No response received from SNMP agent.");
}
}
target.Close();
}
private string GetHost(string ipAddress)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
return entry.HostName;
}
catch
{
return "";
}
}
}
}
Can Anyone is going to help me out for finding the code or give me a way that how can I convert this code to work for Cisco. what Oid it can be?
Recently i have decided to create a plugin for the TFS for tracking work item changes based on ISubscriber interface.
So the workflow would be the following:
1) Work item state changes
2) Plugin catches the WorkItemChangedEvent
3) Send an email to the person specified in the Requester
As the base for my project, i used the following project from CodePlex - The Mail Alert
After i adopted it to my needs and saved compiled binaries in %TFS-DIR%\Microsoft Team Foundation Server 14.0\Application Tier\Web Services\bin\Plugins the TFS restarted the tier and... that's it. On work item change the ProcessEvent method is not called, but it should be.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
using System.Diagnostics;
using System.Xml.Linq;
using System.Xml;
using System.DirectoryServices;
using System.Net.Mail;
using System.Xml.Xsl;
using System.Configuration;
using System.Reflection;
namespace MailAlert
{
public class WorkItemChangedEventHandler : ISubscriber
{
static string serverPath = "";
static string ExternalURL = "";
static string MailAddressFrom = "";
static string SMTPHost = "";
static string Password = "";
static int Port = 25;
static int index = 0;
static string projectCollectionFolder;
static Uri projectCollectionUri;
static WorkItemStore wiStore;
static WorkItem wItem;
static WorkItemChangedEvent workItemChangedEvent;
static string teamProjectPath = "";
static VersionControlServer versionControlServer;
static TfsTeamProjectCollection projectCollection;
static Dictionary<IdentityDescriptor, TeamFoundationIdentity> m_identities = new Dictionary<IdentityDescriptor, TeamFoundationIdentity>(IdentityDescriptorComparer.Instance);
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(WorkItemChangedEvent) };
}
public WorkItemChangedEventHandler()
{
TeamFoundationApplicationCore.Log("WorkItemChangedEvent Started", index++, EventLogEntryType.Information);
}
public EventNotificationStatus ProcessEvent(TeamFoundationRequestContext requestContext, NotificationType notificationType,
object notificationEventArgs, out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: ProcessEvent entered", index++, EventLogEntryType.Information);
statusCode = 0;
properties = null;
statusMessage = String.Empty;
GetTfsServerName();
projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(serverPath));
try
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
workItemChangedEvent = notificationEventArgs as WorkItemChangedEvent;
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: WorkItem " + workItemChangedEvent.WorkItemTitle + " was modified", index++, EventLogEntryType.Information);
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: serverPath - " + serverPath, index++, EventLogEntryType.Information);
projectCollectionFolder = requestContext.ServiceHost.VirtualDirectory.ToString();
projectCollectionUri = new Uri(serverPath + projectCollectionFolder);
projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(projectCollectionUri);
wiStore = projectCollection.GetService<WorkItemStore>();
versionControlServer = projectCollection.GetService<VersionControlServer>();
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: Before process workitem", index++, EventLogEntryType.Information);
ProcessWorkItem();
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: After process workitem", index++, EventLogEntryType.Information);
}
}
catch (Exception ex)
{
TeamFoundationApplicationCore.Log("WorkItemChangedEventHandler: FUCKING EXCEPTION! =>\n" + ex.Message, index++, EventLogEntryType.Error);
}
return EventNotificationStatus.ActionPermitted;
}
private static void GetTfsServerName()
{
try
{
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(assemblyFolder + #"\Settings.xml");
// Declare the xpath for finding objects inside the XML file
XmlNodeList XmlDocNodes = XmlDoc.SelectNodes("/configuration/tfssettings");
XmlNodeList XmlDocExt = XmlDoc.SelectNodes("/configuration/Externaltfssettings");
// Define a new List, to store the objects we pull out of the XML
serverPath = XmlDocNodes[0].InnerText;
ExternalURL = XmlDocExt[0].InnerText;
XmlNodeList XmlDocNodes2 = XmlDoc.SelectNodes("/configuration/appSettings");
foreach (XmlNode mailNode in XmlDocNodes2)
{
foreach (XmlNode varElement in mailNode.ChildNodes)
{
switch (varElement.Attributes["key"].Value)
{
case "MailAddressFrom":
MailAddressFrom = varElement.Attributes["value"].Value;
break;
case "SMTPHost":
SMTPHost = varElement.Attributes["value"].Value;
break;
case "Password":
Password = varElement.Attributes["value"].Value;
break;
case "Port":
Port = Convert.ToInt32(varElement.Attributes["value"].Value);
break;
}
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry("WorkItemChangedEventHandler", ex.Message);
}
}
public string Name
{
get { return "WorkItemChangedEventHandler"; }
}
public SubscriberPriority Priority
{
get { return SubscriberPriority.High; }
}
private static void ProcessWorkItem()
{
var teamProjects = versionControlServer.GetAllTeamProjects(false);
for (int i = 0; i < teamProjects.Length; i++)
{
string teamProjectName = teamProjects[i].Name;
var teamProject = teamProjects[i];
Project teamProjectWI = wiStore.Projects[i];
teamProjectPath = projectCollectionUri + teamProject.Name;
if (workItemChangedEvent.PortfolioProject == teamProjectName)
{
//get the workitem by ID ( CoreFields.IntegerFields[0] == ID ?!)
//check if any of String changed fields
foreach(StringField sf in workItemChangedEvent.ChangedFields.StringFields)
{
//is the State field
if (sf.Name.Equals("State"))
{
//then notify Reuqester
wItem = wiStore.GetWorkItem(workItemChangedEvent.CoreFields.IntegerFields[0].NewValue);
string CollGuid = projectCollection.InstanceId.ToString();
string Requester = wItem.Fields["Requester"].Value.ToString();
string WorkItemId = wItem.Id.ToString();
string mail = GetEmailAddress(Requester);
SendMail(CollGuid, WorkItemId, mail);
}
}
}
}
}
private static string GetEmailAddress(string userDisplayName)
{
DirectorySearcher ds = new DirectorySearcher();
ds.PropertiesToLoad.Add("mail");
ds.Filter = String.Format("(&(displayName={0})(objectCategory=person)((objectClass=user)))", userDisplayName);
SearchResultCollection results = ds.FindAll();
if (results.Count == 0)
{
return string.Empty;
}
ResultPropertyValueCollection values = results[0].Properties["mail"];
if (values.Count == 0)
{
return string.Empty;
}
return values[0].ToString();
}
private static void SendMail(string collID,string workItemId,string tomailAddrees)
{
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = Port;
client.Host = SMTPHost;
client.Timeout = 200000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(MailAddressFrom, Password);
objeto_mail.From = new MailAddress(MailAddressFrom);
objeto_mail.To.Add(new MailAddress(tomailAddrees));
//objeto_mail.CC.Add(new MailAddress("nagarajb#hotmail.com"));
objeto_mail.Subject = "Work Item Changed:"+workItemId;
string mailbody = serverPath+"/tfs/web/wi.aspx?pcguid=" + collID + "&id=" + workItemId;
string mailbody2 = "";
if (ExternalURL.Length > 0)
{
mailbody2 = ExternalURL + "/tfs/web/wi.aspx?pcguid=" + collID + "&id=" + workItemId;
}
string tables = "<table border=1><tr><td>Work Item ID</td><td>" + wItem.Id.ToString() + "</td></tr><tr><td>Title</td><td>" + wItem.Title + "</td></tr><tr><td>State</td><td>" + wItem.State + "</td></tr><tr><td>Assigned To</td><td>" + wItem.Fields["Assigned to"].Value.ToString() + "</td></tr><tr><td>Internal URL</td><td>" + mailbody + "</td></tr><tr><td>External URL</td><td>" + mailbody2 + "</td></tr></table>";
objeto_mail.IsBodyHtml = true;
objeto_mail.Body = "<i>Hi " + wItem.Fields["Requester"].Value.ToString() + ","+"</i></br></br></br>" + tables + " </br></br> Best regards; </br></br>Configuration Management Team</br></br></br>";
client.Send(objeto_mail);
EventLog.WriteEntry("WorkItemChangedEventHandler", "Email Sent");
}
}
}
No errors or exceptions are thrown in the Event Log either. Tracing TFS (trace=true property in web.config) also was of no help.
Maybe someone could help or shed light on this mysterious case?
UPDATE:
Thanks for a reply Giulio Vian!
Here how it goes:
1) I haven't seen the dependencies broken, plus the constructor WorkItemChangedEventHandler is successfully called. That is seen in the Windows Event Log - WorkItemChangedEvent Started message is written.
2) I am not sure how to register the event handler.... i'll look that up
3) I am not sure how this works. I thought just copy-pasting dlls in the appropriate folder will do the trick, and there is no need for an account for the plugin. Mind giving a bit more info on this?
4) yes. Web.config in the main Web config in Application Tier\Web Services
5) Yes. Using an account with Administer rights. if i set a break point in the constructor, it is reached. Any other place in the code is not reached.
Many things can be wrong.
If any dependency is broken, you should see an error in the Event log
If you do not register the "WorkItemChangedEventHandler" event source, no message is written
Can the user account running the plugin access TFS?
How did you enabled the tracing (you pasted a bunch of code, but no configuration)?
Have you attached the debugger to the TFS process and set a breakpoint (do not this on a production TFS)?
We have collected similar suggestions in the documentation for our plugin at
https://github.com/tfsaggregator/tfsaggregator/wiki.
I am trying for my school to use the Bing Map API and use GeocodeAdress. I build this application: http://msdn.microsoft.com/en-us/library/dd221354.aspx and the problem is I get this error every time.
it is at line 62: this method: GeocodeServiceClient geocodeService = new GeocodeServiceClient();
!InvalidOperationException was unhandled
An unhandled exception of type 'System.InvalidOperationException' occurred in System.ServiceModel.dll
Additional information: An endpoint configuration section for contract 'GeocodeService.IGeocodeService' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BingMapsSample.GeocodeService;
using BingMapsSample.SearchService;
using BingMapsSample.ImageryService;
using BingMapsSample.RouteService;
namespace BingMapsSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private String GeocodeAddress(string address)
{
string results = "";
string key = "Validate Bing Map Education Code";
GeocodeRequest geocodeRequest = new GeocodeRequest();
// Set the credentials using a valid Bing Maps key
geocodeRequest.Credentials = new GeocodeService.Credentials();
geocodeRequest.Credentials.ApplicationId = key;
// Set the full address query
geocodeRequest.Query = address;
// Set the options to only return high confidence results
ConfidenceFilter[] filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter();
filters[0].MinimumConfidence = GeocodeService.Confidence.High;
// Add the filters to the options
GeocodeOptions geocodeOptions = new GeocodeOptions();
geocodeOptions.Filters = filters;
geocodeRequest.Options = geocodeOptions;
// Make the geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient();
GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = String.Format("Latitude: {0}\nLongitude: {1}",
geocodeResponse.Results[0].Locations[0].Latitude,
geocodeResponse.Results[0].Locations[0].Longitude);
else
results = "No Results Found";
return results;
}
private string ReverseGeocodePoint(string locationString)
{
string results = "";
string key = "Validate Bing Map Education Code";
ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();
// Set the credentials using a valid Bing Maps key
reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
reverseGeocodeRequest.Credentials.ApplicationId = key;
// Set the point to use to find a matching address
GeocodeService.Location point = new GeocodeService.Location();
string[] digits = locationString.Split(',');
point.Latitude = double.Parse(digits[0].Trim());
point.Longitude = double.Parse(digits[1].Trim());
reverseGeocodeRequest.Location = point;
// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient();
GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = geocodeResponse.Results[0].DisplayName;
else
results = "No Results found";
return results;
}
private string SearchKeywordLocation(string keywordLocation)
{
String results = "";
String key = "Validate Bing Map Education Code";
SearchRequest searchRequest = new SearchRequest();
// Set the credentials using a valid Bing Maps key
searchRequest.Credentials = new SearchService.Credentials();
searchRequest.Credentials.ApplicationId = key;
//Create the search query
StructuredSearchQuery ssQuery = new StructuredSearchQuery();
string[] parts = keywordLocation.Split(';');
ssQuery.Keyword = parts[0];
ssQuery.Location = parts[1];
searchRequest.StructuredQuery = ssQuery;
//Define options on the search
searchRequest.SearchOptions = new SearchOptions();
searchRequest.SearchOptions.Filters =
new FilterExpression()
{
PropertyId = 3,
CompareOperator = CompareOperator.GreaterThanOrEquals,
FilterValue = 8.16
};
//Make the search request
SearchServiceClient searchService = new SearchServiceClient();
SearchResponse searchResponse = searchService.Search(searchRequest);
//Parse and format results
if (searchResponse.ResultSets[0].Results.Length > 0)
{
StringBuilder resultList = new StringBuilder("");
for (int i = 0; i < searchResponse.ResultSets[0].Results.Length; i++)
{
resultList.Append(String.Format("{0}. {1}\n", i + 1,
searchResponse.ResultSets[0].Results[i].Name));
}
results = resultList.ToString();
}
else
results = "No results found";
return results;
}
private void Geocode_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = GeocodeAddress(textInput.Text);
}
private void ReverseGeocode_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = ReverseGeocodePoint(textInput.Text);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
labelResults.Content = SearchKeywordLocation(textInput.Text);
}
}
}
I found the solution line 62 should be:
var geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
Open your web.config file or app.config file. In there you will see a basic and custom binding configuration for the service. Remove the custom binding section. Clean and build your project and it should work.
As a side note. The Bing Maps SOAP services are really old and limited in functionality. They were released about 8 years ago. A newer REST based service was released about 4 years ago. REST is faster, has smaller response packages and has more features. You can find out more about the Bing Maps REST services here: http://msdn.microsoft.com/en-us/library/ff701713.aspx
The below code reads a texts file, formats it, displays any error and insert the data into SQL Server Database. I wrote the below code previously in Visual Basic, now I am trying to rewrite the code int C# but it is not working.
I cannot get the fields indicated to insert into a database: I am trying to get the records without errors to insert into the database even when their are error with other rows.
This was a project I did piece by piece as I am still learning this stuff, so please forgive my ignorance. The database portion seems fine so I did not post it but I can if requested.
Classes from file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace ConsoleApplication1
{
class ClsMethods
{
public class MemberInfo
{
public static string MemberPhone;
public static string MemberName;
public static string MemberAddr1;
public static string MemberAddr2;
public static string MemberCity;
public static string MemberState;
public static string MemberZip;
}
public class ErrLog
{
public static int RowNum;
public static List<string> Err;
public ErrLog(int row)
{
RowNum = row;
Err = new List<string>();
}
public ErrLog()
{
Err = new List<string>();
}
}
}
}
MainCode:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
public static class MainModule
{
static List<ClsMethods.ErrLog> ErrList;
public static void Main()
{
string strFilename = null;
FileInfo fiFile = default(FileInfo);
StreamReader srData = default(StreamReader);
string strRecord = "";
List<ClsMethods.MemberInfo> MbrList = default(List<ClsMethods.MemberInfo>);
ClsMethods.MemberInfo MbrInfo = default(ClsMethods.MemberInfo);
int successCount = 0;
int failedCount = 0;
int totalCount = 0;
ErrList = new List<ClsMethods.ErrLog>();
strFilename = "C:\\EMP\\Member.csv";
fiFile = new FileInfo(strFilename);
if (fiFile.Exists)
{
if (fiFile.Length > 0)
{
MbrList = new List<ClsMethods.MemberInfo>();
srData = new StreamReader(strFilename);
while (srData.Peek() > 0)
{
try
{
strRecord = srData.ReadLine().Replace("\"", "");
totalCount = totalCount + 1;
String[] rec = strRecord.Split(",".ToCharArray());
if ((ValidateRow(rec, totalCount)))
{
MbrInfo = new ClsMethods.MemberInfo();
ClsMethods.MemberInfo.MemberPhone = rec[0];
ClsMethods.MemberInfo.MemberName = rec[1];
ClsMethods.MemberInfo.MemberAddr1 = rec[2];
ClsMethods.MemberInfo.MemberAddr2 = rec[3];
ClsMethods.MemberInfo.MemberCity = rec[4];
ClsMethods.MemberInfo.MemberState = rec[5];
ClsMethods.MemberInfo.MemberZip = rec[6];
MbrList.Add(MbrInfo);
}
}
catch (Exception ex)
{
Console.WriteLine("READ: " + ex.Message);
srData.Close();
srData.Dispose();
}
Console.WriteLine(strRecord);
}
foreach (ClsMethods.MemberInfo emp in MbrList)
{
if ((ClsDatabase.InsertMemberInfo(MbrInfo)))
{
successCount = successCount + 1;
}
else
{
failedCount = failedCount + 1;
}
}
Console.WriteLine("Total rows: {0} ", totalCount);
Console.WriteLine("Records without Errors: {0} ", MbrList.Count);
Console.WriteLine("Records with errors: {0} ", ErrList.Count);
Console.WriteLine("Inserted successfully: " + successCount.ToString());
Console.WriteLine("Failed: " + failedCount.ToString());
if ((ErrList.Count > 0))
{
Console.WriteLine("If you want to display errors press D. If you want to store errors in log file press F.");
ConsoleKeyInfo cki = default(ConsoleKeyInfo);
cki = Console.ReadKey();
Console.WriteLine();
string res = "";
res = cki.Key.ToString(res.ToUpper());
if ((res == "D"))
{
DisplayErrors();
}
else if ((res == "F"))
{
WriteErrorsToFile();
}
}
}
else
{
Console.WriteLine("File " + strFilename + " is empty");
}
}
else
{
Console.WriteLine("File " + strFilename + " doesn't exists");
}
Console.WriteLine("Program End. Press any key to exit");
Console.ReadKey();
Environment.Exit(0);
}
public static void DisplayErrors()
{
foreach (ClsMethods.ErrLog err in ErrList)
{
foreach (string errDescr in ClsMethods.ErrLog.Err)
{
Console.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
}
}
}
public static void WriteErrorsToFile()
{
string path = "C:\\Log\\log.txt";
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
using (StreamWriter outfile = new StreamWriter(File.Create(path)))
{
foreach (ClsMethods.ErrLog err in ErrList)
{
foreach (string errDescr in ClsMethods.ErrLog.Err)
{
outfile.WriteLine("Line " + ClsMethods.ErrLog.RowNum.ToString() + ": " + errDescr);
}
}
}
}
public static bool ValidateRow(string[] rec, int rowIndex)
{
ClsMethods.ErrLog Err = new ClsMethods.ErrLog();
if ((rec.Length != 7))
{
ClsMethods.ErrLog.Err.Add("Wrong number of values in row");
}
else
{
rec[0] = rec[0].Replace("-", "");
if ((string.IsNullOrEmpty(rec[0])))
{
ClsMethods.ErrLog.Err.Add("Phone is empty");
}
if ((string.IsNullOrEmpty(rec[1])))
{
ClsMethods.ErrLog.Err.Add("Name is empty");
}
if ((string.IsNullOrEmpty(rec[2])))
{
ClsMethods.ErrLog.Err.Add("Address is empty");
}
if ((string.IsNullOrEmpty(rec[4])))
{
ClsMethods.ErrLog.Err.Add("City is empty");
}
if ((string.IsNullOrEmpty(rec[5])))
{
ClsMethods.ErrLog.Err.Add("State is empty");
}
if ((string.IsNullOrEmpty(rec[6])))
{
ClsMethods.ErrLog.Err.Add("Zip is empty");
}
}
if ((ClsMethods.ErrLog.Err.Count > 0))
{
ClsMethods.ErrLog.RowNum = rowIndex;
ErrList.Add(Err);
return false;
}
else
{
return true;
}
}
}
}
}
Database Connection and Parameters:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
namespace ConsoleApplication1
{
class ClsDatabase
{
public static SqlConnection GetConnection()
{
SqlConnection InitCnt = null;
InitCnt = new SqlConnection();
InitCnt.ConnectionString = "Server=MyDB;database=Example;Trusted_Connection=true;";
try
{
InitCnt.Open();
}
catch (Exception ex)
{
InitCnt.Close();
InitCnt.Dispose();
}
return InitCnt;
}
public static bool InsertMemberInfo(ClsMethods.MemberInfo MbrInfo)
{
SqlConnection InitCnt = default(SqlConnection);
SqlCommand InitCmd = default(SqlCommand);
InitCnt = GetConnection();
if ((InitCnt != null))
{
InitCmd = new SqlCommand();
InitCmd.Connection = InitCnt;
InitCmd.CommandText = "uspInsertMemberInformation";
InitCmd.CommandType = CommandType.StoredProcedure;
InitCmd.Parameters.Add(new SqlParameter("#MemberPhone", SqlDbType.NVarChar, 10));
InitCmd.Parameters["#MemberPhone"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberPhone"].Value = ClsMethods.MemberInfo.MemberPhone;
InitCmd.Parameters.Add(new SqlParameter("#MemberName", SqlDbType.NVarChar, 50));
InitCmd.Parameters["#MemberName"].Value = ClsMethods.MemberInfo.MemberName;
InitCmd.Parameters["#MemberName"].Value = ClsMethods.MemberInfo.MemberName;
InitCmd.Parameters.Add(new SqlParameter("#MemberAddr1", SqlDbType.NVarChar, 30));
InitCmd.Parameters["#MemberAddr1"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberAddr1"].Value = ClsMethods.MemberInfo.MemberAddr1;
InitCmd.Parameters.Add(new SqlParameter("#MemberAddr2", SqlDbType.NVarChar, 30));
InitCmd.Parameters["#MemberAddr2"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberAddr2"].Value = ClsMethods.MemberInfo.MemberAddr2;
InitCmd.Parameters.Add(new SqlParameter("#MemberCity", SqlDbType.NVarChar, 20));
InitCmd.Parameters["#MemberCity"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberCity"].Value = ClsMethods.MemberInfo.MemberCity;
InitCmd.Parameters.Add(new SqlParameter("#MemberState", SqlDbType.NChar, 2));
InitCmd.Parameters["#MemberState"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberState"].Value = ClsMethods.MemberInfo.MemberState;
InitCmd.Parameters.Add(new SqlParameter("#MemberZip", SqlDbType.NVarChar, 9));
InitCmd.Parameters["#MemberZip"].Direction = ParameterDirection.Input;
InitCmd.Parameters["#MemberZip"].Value = ClsMethods.MemberInfo.MemberZip;
try
{
InitCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
return false;
}
finally
{
InitCmd.Parameters.Clear();
InitCnt.Close();
}
}
return true;
}
}
}
Some really peculiar stuff there:
ClsMethods contains only classes and is not used; remove it.
MemberInfo contains only static fields, so every instance must always contain the same data.
ErrLog contains only a static field so, again, every instance will always contain the same data.
Main pointlessly sets a bunch of variables to default, which is always null, which is redundant. Why are you doing that?
MainModule is also redundant and should be removed.
All variables are global, which is unnecessary and risky.
MbrInfo = new ClsMethods.MemberInfo(); is useless because all fields are static, you will just be overwriting what is already there.
ClsDatabase.InsertMemberInfo(MbrInfo) will always pass the last record as many times as there are records in the file. I'm guessing you want ClsDatabase.InsertMemberInfo(emp). See why globals are bad?
InsertMemberInfo ignores the parameter you pass and uses the single static value for every parameter.
The default SqlParameter.Direction is Input, you don't have to reset it.
I wouldn't add "Member" to the front to every field; it's already in the class name. I'm guessing what you want is:
public class MemberInfo
{
public string Phone;
public string Name;
public string Addr1;
public string Addr2;
public string City;
public string State;
public string Zip;
}
Then in Main you can call:
MemberInfo mi = new MemberInfo();
mi.Phone = rec[0];
mi.Name = rec[1];
mi.Addr1 = rec[2];
mi.Addr2 = rec[3];
mi.City = rec[4];
mi.State = rec[5];
mi.Zip = rec[6];
MbrList.Add(mi);
You use the word Err to refer to a class, the log, and instance variables. This is very confusing. I suggest something like:
public class ErrLog
{
public int RowNum;
public List<string> Messages;
public ErrLog(int row)
: base()
{
RowNum = row;
}
public ErrLog()
{
Messages = new List<string>();
}
}
Your InsertMemberInfo should look more like this:
var sp = new SqlParameter("#MemberPhone", SqlDbType.NVarChar, 10);
sp.Value = MbrInfo.whatever;
InitCmd.Parameters.Add(sp);
Don't do this:
try
{
InitCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
return false;
}
That will discard the reason the procedure failed. Just do this:
InitCmd.ExecuteNonQuery();
Exceptions. Use them. A few more weird things in your code; start with what I've shown.