I am getting the error
"An item with the same key has already been added"
in production randomly.if i execute the below code in local i am not getting the issue.please suggestion needed to solve this issue.
//check for whether Midas.DAB is Enabled in the App.Config File
if (ProcessMidasDab)
{
var dvFilteredMidasDabDetails = new DataView(dtMidasDabandSurgDetails) {
RowFilter = "not (LastReceivedOnForDAB is null)" };
dtCmMidasDabAlerts.Columns.Add("ClientID");
dtCmMidasDabAlerts.Columns.Add("LastFileReceivedDate");
dtCmMidasDabAlerts.Columns.Add("SendingSystem");
//Get the Cut-off time for Midas.DAB from the App.config.
var timeStamp = ConfigurationManager.AppSettings["TimeLapseforMidasDABinhrs"];
//Logic to check the Feed for Midas.DAB
foreach (DataRowView dv in dvFilteredMidasDabDetails)
{
midasDabClientList.Add(Convert.ToInt32(dv["ClientID"]));
var timeDifference =
(DateTime.Now - Convert.ToDateTime(dv["LastReceivedOnForDAB"])).TotalHours;
if (timeDifference > Convert.ToDouble(timeStamp))
{
var drNewRow = dtCmMidasDabAlerts.NewRow();
drNewRow["ClientID"] = dv["ClientID"];
drNewRow["LastFileReceivedDate"] = dv["LastReceivedOnForDAB"];
drNewRow["SendingSystem"] = "Midas.DAB";
dtCmMidasDabAlerts.Rows.Add(drNewRow);
}
}
dabclients = midasDabClientList;
}
You have two time assign this
drNewRow["Clientid"] = 12;
drNewRow["ClientID"] = dv["ClientID"];
Please remove this one
drNewRow["Clientid"] = 12;
and also you have two time assigned this
dtCmMidasDabAlerts.Columns.Add("ClientID");
Related
I have a utility that reads the status of MicrosoftBizTalk Server resources .. specifically the ReceiveLocation component. My problem is that the program is submitting multiple entries of each item i.e each item in the data returned is being multiplied by 25 such that instead of persisting only 5 rows the data being persisted is 125. So for example instead of having just 1 row for my first row returned i have 25.
This is my program :
public List<BizTalk> GetBizTalkServicesStatistics()
{
List<BizTalk> model = new List<BizTalk>();
try
{
//Create the WMI search object.
ManagementObjectSearcher Searcher = new ManagementObjectSearcher();
ConnectionOptions options = new ConnectionOptions
{
Username = "+username+",
Password = "+password+",
Authority = "+domain+"
};
var server = "+server+";
// create the scope node so we can set the WMI root node correctly.
ManagementScope Scope = new ManagementScope("\\\\" + server + "\\root\\MicrosoftBizTalkServer", options);
Searcher.Scope = Scope;
// Build a Query to enumerate the MSBTS_ReceiveLocation instances if an argument
// is supplied use it to select only the matching RL.
//if (args.Length == 0)
SelectQuery Query = new SelectQuery();
Query.QueryString = "SELECT * FROM MSBTS_ReceiveLocation";
// else
//Query.QueryString = "SELECT * FROM MSBTS_ReceiveLocation WHERE Name = '" + args[0] + "'";
// Set the query for the searcher.
Searcher.Query = Query;
// Execute the query and determine if any results were obtained.
ManagementObjectCollection QueryCol = Searcher.Get();
// Use a bool to tell if we enter the for loop
// below because Count property is not supported
bool ReceiveLocationFound = false;
// Enumerate all properties.
foreach (ManagementBaseObject envVar in QueryCol)
{
// There is at least one Receive Location
ReceiveLocationFound = true;
PropertyDataCollection envVarProperties = envVar.Properties;
foreach (PropertyData envVarProperty in envVarProperties)
{
BizTalk bizTalk = new BizTalk();
bizTalk.Name = Convert.ToString(envVar["Name"]);
bizTalk.TransportType = Convert.ToString(envVar["AdapterName"]);
bizTalk.Uri = Convert.ToString(envVar["InboundTransportURL"]);
bizTalk.Status = Convert.ToString(envVar["Name"]);
bizTalk.ReceiveHandler = Convert.ToString(envVar["HostName"]);
bizTalk.ReceivePort = Convert.ToString(envVar["ReceivePortName"]);
bizTalk.RunDate = DateTime.Now;
bizTalk.ApplicationId = 24;
bizTalk.ServerId = 8;
bizTalk.InstanceName = "FBCZOP";
model.Add(bizTalk);
}
}
if (!ReceiveLocationFound)
{
Console.WriteLine("No receive locations found matching the specified name.");
}
}
catch (Exception excep)
{
ExceptionLogger.SendErrorToText(excep);
}
return model;
}
Save Function
public void SaveStatistics(BizTalk entity)
{
List<BizTalk> ServerInfo = new List<BizTalk>();
ServerInfo = GetBizTalkServicesStatistics();
foreach (var di in ServerInfo)
{
entity.RunDate = di.RunDate;
entity.Name = di.Name;
entity.Status = di.Status;
entity.Uri = di.Uri;
entity.InstanceName = di.InstanceName;
entity.ReceivePort = di.ReceivePort;
entity.TransportType= di.TransportType;
entity.RunDate = DateTime.Now;
entity.ReceiveHandler = di.ReceiveHandler;
entity.ServerId = entity.ServerId;
entity.ApplicationId = entity.ApplicationId;
appEntities.BizTalk.Add(entity);
appEntities.SaveChanges();
}
}
When i step through the code variable envVarProperties shows record count as 125 under envVarProperties << ResultsView :
Link 1
whilst QueryCol variable shows count of 5 :
Link 2
It looks like you're iterating an extra time in your GetBizTalkServicesStatistics() method.
Remove the foreach loop that starts with foreach (PropertyData envVarProperty in envVarProperties). This is looping through each property the object has (All 25 properties) for each instance (5 instances)... 25 * 5 = 125 values you are retrieving. You only want to iterate through your instances and pull the properties you want. That way you end up with 5 objects in your model object.
I'd suggest maybe something like this (untested because I don't have BizTalk)
public List<BizTalk> GetBizTalkServicesStatistics()
{
List<BizTalk> model = new List<BizTalk>();
try
{
//Create the WMI search object.
ConnectionOptions options = new ConnectionOptions
{
Username = "+username+",
Password = "+password+",
Authority = "+domain+"
};
var server = "+server+";
// create the scope node so we can set the WMI root node correctly.
ManagementScope Scope = new ManagementScope("\\\\" + server + "\\root\\MicrosoftBizTalkServer", options);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, new ObjectQuery("SELECT * FROM MSBTS_ReceiveLocation"));
// Enumerate all properties.
foreach (ManagementObject instance in Searcher.Get())
{
{
BizTalk bizTalk = new BizTalk();
bizTalk.Name = instance.Properties["Name"]?.Value?.ToString();
bizTalk.TransportType = instance.Properties["AdapterName"]?.Value?.ToString();
bizTalk.Uri = instance.Properties["InboundTransportURL"]?.Value?.ToString();
bizTalk.Status = instance.Properties["Name"]?.Value?.ToString();
bizTalk.ReceiveHandler = instance.Properties["HostName"]?.Value?.ToString();
bizTalk.ReceivePort = instance.Properties["ReceivePortName"]?.Value?.ToString();
bizTalk.RunDate = DateTime.Now;
bizTalk.ApplicationId = 24;
bizTalk.ServerId = 8;
bizTalk.InstanceName = "FBCZOP";
model.Add(bizTalk);
}
}
// Determine
if (model.Count == 0)
{
Console.WriteLine("No receive locations found matching the specified name.");
}
}
catch (Exception excep)
{
ExceptionLogger.SendErrorToText(excep);
}
return model;
}
Also, this can be simplified more if you remove the connectionoptions (unless you are hard coding credentials which is highly advised against). If you are just using the identity of the executing user, that data is not needed.
-Paul
You are adding the same entity 25 times and overwrite its properties by reference. You need to initialize a new entity inside your loop:
foreach (var di in ServerInfo)
{
var entity = new BizTalk();
entity.RunDate = di.RunDate;
entity.Name = di.Name;
entity.Status = di.Status;
entity.Uri = di.Uri;
entity.InstanceName = di.InstanceName;
entity.ReceivePort = di.ReceivePort;
entity.TransportType= di.TransportType;
entity.RunDate = DateTime.Now;
entity.ReceiveHandler = di.ReceiveHandler;
entity.ServerId = entity.ServerId;
entity.ApplicationId = entity.ApplicationId;
appEntities.BizTalk.Add(entity);
appEn.SaveChanges();
}
}
As you don't show the code where "SaveStatistics" is called it's not sure this will fix your complete problem, but it's at least one method that does not do what you expect it to do.
I'm new in c# , but i can do the basics. i need to change all the values of a column and then update the datagrid. The values are in 20170202 format and i want them like 2017-02-02. the method i did works fine but when i try to set the value to the column it wont change.
here is the code:
private void fixAlldates(DataGridView dataGridView2)
{
string aux1 = "";
for (int x = 0; x < dataGridView2.Rows.Count; x++)
{
if (dataGridView2.Rows[x].Cells[4].Value.ToString() != null)
{
aux1 = dataGridView2.Rows[x].Cells[4].Value.ToString();
dataGridView2.Rows[x].Cells[4].Value = fixDate(aux1);
}
if (dataGridView2.Rows[x].Cells[5].Value.ToString() != null)
{
dataGridView2.Rows[x].Cells[5].Value = fixDate(dataGridView2.Rows[x].Cells[5].Value.ToString());
}
dataGridView2.Refresh();
MessageBox.Show(fixDate(aux1); ----> shows result like i want ex: 2017-02-02
MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); ----> shows 2070202
}
}
private string fixDate(string p)
{
if (p == null) return "No especificado";
String fecha = "" + p.Substring(0, 4) + "-" + p.Substring(4, 2) + "-" + p.Substring(6, 2) + "";
return fecha;
}
sorry for my bad english , im a little bit rusty
Edit:
I fill the data with bindingSource.
private void LlenarProductos(string rut)
{
this.rut = rut;
POLbindingSource1.DataSource = null;
dataGridView2.DataSource = null;
DataClasses1DataContext dc = new DataClasses1DataContext();
dc.CommandTimeout = 0;
System.Data.Linq.Table<ASE_PRODUCTOASEGURADO> producto = dc.GetTable<ASE_PRODUCTOASEGURADO>();
var todoprod = from p in producto
where p.RUT == int.Parse(rut)
select new
{
p.POLIZA,
p.SOCIO,
p.SUCURSAL,
p.COD_PROPUESTA,
p.FECHA_ALTA_COTI,
p.FECHA_ALTA_VCTO,
p.NOMBRE_PRODUCTO
};
POLbindingSource1.DataSource = todoprod; // binding source
dataGridView2.DataSource = POLbindingSource1; // filll
this.dataGridView2.Columns["POLIZA"].HeaderText = "Poliza";
this.dataGridView2.Columns["Socio"].HeaderText = "Socio";
this.dataGridView2.Columns["Sucursal"].HeaderText = "Sucursal";
this.dataGridView2.Columns["COD_PROPUESTA"].HeaderText = "Propuesta";
this.dataGridView2.Columns["FECHA_ALTA_COTI"].HeaderText = "Fecha Cotizacion";
this.dataGridView2.Columns["FECHA_ALTA_VCTO"].HeaderText = "Fecha Vencimiento";
this.dataGridView2.Columns["NOMBRE_PRODUCTO"].HeaderText = "Producto";
// fixAlldates(dataGridView2);
}
From msdn https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.value(v=vs.110).aspx.
The Value property is the actual data object contained by the cell.
So basically the line MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); is getting the value of the underlying data, whereas MessageBox.Show(fixDate(aux1); is actually formatting the date as you require.
You're overlooking the fact that although you're seeing the data in the grid in a specific way, you're not actually changing the data itself.
UPDATE
To actually edit the data in a cell see here
i need copy and paste some records of my table with just but change one field.
here is my code:
using (ClearWhiteDBEntities cwContext = new ClearWhiteDBEntities())
{
var qlstfld = from lstflds in cwContext.tblListFields
where lstflds.listId == theLongSrc
select lstflds;
foreach (var item in qlstfld)
{
tblListField lstFldRow = new tblListField
{
name = item.name,
filterFieldId = item.filterFieldId,
listId = theLongDes, //this field must be change in paste
continueById = item.continueById,
destinationId = item.destinationId,
conditionId = item.conditionId,
userId = userId,
date = Convert.ToDateTime(DateTime.Now.ToShortDateString()),
time = DateTime.Now.TimeOfDay,
IP = trueIp
};
cwContext.AddTotblListFields(lstFldRow);
cwContext.SaveChanges();
}
}
but i get this error:
an error accured white starting a transaction on the provider connection. see the inner exception for details.
what is best solution to copy and paste records but change one field?
If you are using change tracking:
using (ClearWhiteDBEntities cwContext = new ClearWhiteDBEntities())
{
var qlstfld = from lstflds in cwContext.tblListFields
where lstflds.listId == theLongSrc
select lstflds;
foreach (var item in qlstfld)
{
cwContext.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Added);
item.Id = 0;
item.listId = theLongDes; //this field must be change in paste
}
cwContext.SaveChanges();
}
I am trying to change date to all workouts in the list, the other properties are working fine, its only when I change Date i get problem. I have tried different trouble shooting, but none have worked. I have tried with using updatedWorkout.Date as workoutStart = out of range. If I use old.Date, then, how can I add the new date with 7days a part ?
Maybe there is a better way to do this?
Here's my method:
private int UpdateForAllWorkouts(IWorkoutCommand updatedWorkout)
{
try
{ // get schedule
var schedule = _scheduleRepository.GetIncludeWorkouts(updatedWorkout.ScheduleId);
// get workouts within the schedule by schedule id
var workout = schedule.Workouts.FirstOrDefault(w => w.Id == updatedWorkout.Id);
for (var workoutStart = workout.Date; workoutStart <= schedule.ToDate; workoutStart = workoutStart.AddDays(7))
{
// get specdfic workout by workout id and start time
var old = schedule.Workouts.Single(w => w.Date == workoutStart && w.StartTime == workout.StartTime);
var tmp = new Model.Workout
{
Id = old.Id,
CourseId = updatedWorkout.CourseId,
InstructorId = updatedWorkout.InstructorId,
Date = //<---problem
StartTime = updatedWorkout.StartTime,
EndTime = updatedWorkout.EndTime,
ScheduleId = updatedWorkout.ScheduleId,
WeekOffSet = updatedWorkout.WeekOffSet.Days
};
}
return updatedWorkout.Id;
}
catch (Exception ex)
{
throw new Exception("");
}
}
thx for helping!
I think you can use a loop for 7.
like this :
var workoutStart = workout.Date;
while(true){
if(workoutStart <= schedule.ToDate){
// Do something
}else{
break;
}
workoutStart = workoutStart.AddDays(7);
}
Please consider to check the value of our DateTime properties.Their values could be less than your SQL server allow for datetime field.
What is the Date value of updatedWorkOut object before you assign "tmp" object ?
Is your "old" object null or what is the value of date ?
your code seems to be ok. the problem underlies the value of DateTime properties and fields.
i have this function
private static void DeleteEvent(CalendarService service, string pTitle,DateTime pDate)
{
FeedQuery query = new FeedQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
AtomFeed calFeed = service.Query(query);
foreach (AtomEntry entry in calFeed.Entries)
{
if (pTitle.Equals(entry.Title.Text))
{
entry.Delete(); break;
}
}
}
how i can delete a event by title and date ?
These might help:
http://code.google.com/apis/calendar/data/2.0/developers_guide_dotnet.html#DeletingEvents
http://code.google.com/apis/calendar/data/2.0/developers_guide_dotnet.html#RetrievingEvents
I'd guess something like the following might work:
EventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full");
query.StartDate = ...;
query.EndDate = ...;
EventFeed feed = service.Query(query);
foreach (var entry in feed.Entries)
{
if (pTitle.Equals(entry.Title.Text))
{
entry.Delete(); break;
}
}
Although the above solution will work but I would suggest another approach. Instead of traversing all the events every time and deleting if found, why not ask Google to find the specific event for you. It can be done by using ExtendedProperty using the approach below
Assign an ID (same as you set in your DB) to each event you add.
When deleting you pass the ID to delete and use Query to fetch it for you
Delete the specific event
Google.GData.Calendar.EventEntry Entry = new Google.GData.Calendar.EventEntry();
//create the ExtendedProperty and add the EventID in the new event object,
//so it can be deleted / updated later
ExtendedProperty oExtendedProperty = new ExtendedProperty();
oExtendedProperty.Name = "EventID";
oExtendedProperty.Value = GoogleAppointmentObj.EventID;
Entry.ExtensionElements.Add(oExtendedProperty);
string ThisFeedUri = "http://www.google.com/calendar/feeds/" + CalendarID
+ "/private/full";
Uri postUri = new Uri(ThisFeedUri);
//create an event query object and attach the EventID to it in Extraparameters
EventQuery Query = new EventQuery(ThisFeedUri);
Query.ExtraParameters = "extq=[EventID:" + GoogleAppointmentObj.EventID + "]";
Query.Uri = postUri;
//Find the event with the specific ID
EventFeed calFeed = CalService.Query(Query);
//if search contains result then delete
if (calFeed != null && calFeed.Entries.Count > 0)
{
foreach (EventEntry SearchedEntry in calFeed.Entries)
{
SearchedEntry.Delete();
break;
}
}