I want ask you one problem that I have with one query to the System table.
This is the code that I have wrong.
string current_query = "*[(System[TimeCreated[#SystemTime > '" + dateini + "']]) and (System[TimeCreated[#SystemTime < '" + datenext + "']])]";
Console.WriteLine(current_query);
EventLogQuery eventsQuery = new EventLogQuery(log_location, PathType.FilePath, current_query);
EventLogReader logReader = new EventLogReader(eventsQuery);
The dateini and datenext are DateTime variables.I think that the problem is that I read the table two times. But I need read two times because I need obtain the logs of the System of one full day and I think I must compare between two System Times.
Any suggestion that how remake the consult.
UPDATE:
I try this query with the same result.
string current_query = "*[(Event/System/TimeCreated/#SystemTime > " + dateini + ") and (Event/System/TimeCreated/#SystemTime < " + datenext + ")]";
Console.WriteLine(current_query);
EventLogQuery eventsQuery = new EventLogQuery(log_location, PathType.FilePath, current_query);
EventLogReader logReader = new EventLogReader(eventsQuery);
Please I need help because I don't know which is the error in the Query.
TimeCreated is of the form:
<TimeCreated SystemTime="2013-08-15T16:21:21.000000000Z" />
is your datetime correct?
Shouldn't the query be more like:
Event/System/TimeCreated/#SystemTime
See MSDN and reading-event-logs-efficiently-using-c for some examples.
EDIT
Why are you using > and lt; ? Change lt; to <
This turned out to be the problem.
Related
I found some threads here in the forum related to this problem but they didn't help me. I just want to update my database with a date value. These come from a Textfile (written there as 2014-10-02 for example). Now I tried this (which was mentioned in the other threads):
String connectionQuery = form1.conString.Text;
SqlConnection connection = new SqlConnection(connectionQuery);
SqlCommand sqlComInsert = new SqlCommand(#"INSERT INTO [" + form1.tableName.Text + "] ([" + form1.CusId.Text + "],["+ form1.date.Text +"],[" + form1.cusName.Text + "]) VALUES('" + cusId[i] + "',convert(date,'" + date[i] + "',104),'" + "','" + cusName[i] + "')", connection);
sqlComInsert.Connection.Open();
sqlComInsert.ExecuteNonQuery();
sqlComInsert.Connection.Close();
Now when I leave the "'" out ("',convert / "',104)) he tells me that the syntax is incorrect near 2013 (the beginning of my date). When I write it like above then I get:
String or binary data would be truncated.
What is this? I tried also to convert the date with:
for (int i = 0; i < typeDelDate.Count; i++)
{
unFormatedDate = date[i];
formatedDate = unFormatedDate.ToString("dd/MM/yyyy");
dateFormat.Add(formatedDate);
}
but I get still the same errors. How can I update my values? the column type is "date".
Use parametrized queries instead of slapping strings together:
var commandText = "insert (column) values (#dt);";
var cmd = new SqlCommand(commandText, connection);
cmd.Parameters.AddWithValue("dt", DateTime.ParseExact(dateString, "yyyy-MM-dd"));
cmd.ExecuteNonQuery();
Do not pass values into queries by adding strings - if possible, you should always use parameters. It saves you a lot of trouble converting to proper values (different for different locales etc.), it's more secure, and it helps performance.
I can insert my XML easily into my database table, but i follow this exhausting manner as seen in my down code using LINK, which is perfectly tested. But, I wonder if I can find a way to read all my XML descendants elements of "Level" node, using iteration of all child tagnames, because when I make any change to my XML file, I would have to change my LINK code once again,and usually i'll face some errors when i use this exhausting manner. Please help improve this code:
try
{
XElement d = XElement.Parse(richTextBox1.Text.ToString());
var people = (from Level in d.Descendants("Level")
select new
{
ID = Convert.ToInt32(Level.Element("ID").Value),
Day1 = Level.Element("Day1").Value,
Day2 = Level.Element("Day2").Value,
Day3 = Level.Element("Day3").Value,
Day4 = Level.Element("Day4").Value,
Day5 = Level.Element("Day5").Value,
Day6 = Level.Element("Day6").Value,
Day7 = Level.Element("Day7").Value
}).ToList();
foreach (var item in people)
{
//Insert and Update
datacommand1.CommandText = "Insert Into MyTable(ID,Day1,Day2,Day3,Day4,Day5,Day6,Day7) values(" + item.ID + "," + "','" + item.Day1 + "','" + item.Day2 + "','" + item.Day3 + "','" + item.Day4 + "','" + item.Day5 + "','" + item.Day6 + "','" + item.Day7 + "')";
datacommand1.ExecuteNonQuery();
}
}
my XML file seems like that:
<level>
<id> 101 </id>
<Day1> task 1</Day1>
<Day2> task 2</Day2>
<Day3> task 3</Day3>
<Day4> task 4</Day4>
<Day5> task 5</Day5>
<Day6> task 6</Day6>
<Day7> task7 </Day7>
</level>
Instead of declaring one variable for each tag in the file, you may want to try to iterate over all them, extracting the name and the value for each one and composing the SQL statement at runtime from those, no matter what they are. Try something like this:
IEnumerable<XElement> items = d.Descendants("level").Elements();
string names = string.Empty;
string values = string.Empty;
foreach (XElement item in items)
{
names += item.Name + ",";
values += "#" + item.Name + ",";
IDbDataParameter parameter = datacommand1.CreateParameter();
parameter.ParameterName = "#" + item.Name;
parameter.DbType = DbType.String;
parameter.Value = item.Value;
datacommand1.Parameters.Add(parameter);
}
datacommand1.CommandText = "INSERT INTO MyTable (" + names.Substring(names.Length - 1) + ") VALUES (" + values.Substring(values.Length - 1) + ");";
datacommand1.ExecuteNonQuery();
This builds the command on the fly, based on the XML structure, and fills its parameters with the data there. But doing so relies on the fact that the table structure will be exactly the same as in the file, and still needs manual schema updating when the structure changes, but as long as they're in sync it should be fine.
EDIT
About datatypes, there are 2 choices I can think of. Leave as it is, sending everything as strings no matter what, and rely on the DB engine to parse, validate and turn those into numbers (depending on what DB you're using, that may be possible or not, but I guess it's not rare to see). Or modify the code to separate the special fields apart from the loop (and excluding from it) and add those one by one, specifying their types accordingly. This is easy to do if the numeric columns are fixed, like the ID, and everything else is text.
I've got an ASP.NET 4.0 C# web application that allows multiple users to update rows in the SQL Server DB at the same time. I'm trying to come up with a quick system that will stop USER1 from updating a row that USER2 updated since USER1's last page refresh.
The problem I'm having is that my web application always updates the row, even when I think it shouldn't. But when I manually run the query it only updates when I think it should.
This is my SQL query in C#:
SQLString = "update statuses set stat = '" + UpdaterDD.SelectedValue +
"', tester = '" + Session["Username"].ToString() +
"', timestamp_m = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +
"' where id IN (" + IDs + ") and timestamp_m < '" + PageLoadTime + "';";
And here's a 'real world' example:
SQLString = "update statuses set stat = 'PASS', tester = 'tester007',
timestamp_m = '2013-01-23 14:20:07.221' where id IN (122645) and
timestamp_m < '2013-01-23 14:20:06.164';"
My idea was that this will only update if no other user has changed this row since the user last loaded the page. I have formatted PageLoadTime to the same formatting as my SQL Server DB, as you can see with DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), but something still isn't right.
Does anyone know why I get two different results? Is what I want to do even possible?
I really think the problem is that the page load time is not being set correctly, or is being set immediately before the DB call. For debugging, you may try hardcoding values into it that you know will allow or disallow the insert.
Here's a parameterized version of what you have. I also am letting the DB server set the timestamp to its current time instead of passing a value. If your DB server and your Web server may not have their time of day in synch, then set it yourself.
Using parameterization, you don't have to worry about whether the date/time format is correct or not. I don't know what the DB types are of stat, tester, and timestamp_m so adding the parameter DB type may need adjusting.
string sql = "update statuses set stat = #stat, tester = #tester" +
", timestamp_m = getdate()" +
" where id IN (" + IDs + ") and timestamp_m < #pageLoadTime";
SQLConnection conn = getMeASqlConnection();
SQLCommand cmd = new SQLCommand(sql, conn);
cmd.Parameters.Add("#stat", System.Data.SqlDbType.NVarChar).Value = UpdaterDD.SelectedValue;
cmd.Parameters.Add("#tester", System.Data.SqlDbType.NVarChar).Value = Session["Username"].ToString();
// Here, pageLoadTime is a DateTime object, not a string
cmd.Parameters.Add("#pageLoadTime", System.Data.SqlDbType.DateTime).Value = pageLoadTime;
I am working on tfs workitem. I am trying to fetch the workitem collection using query, i am getting the following error. Any help me please?
[System.ChangedDate] > '4/19/06 1:00 PM' the following error is returned "You cannot supply a time with the date when running a query using date precision. The error is caused by «[System.ChangedDate] > '4/19/06 1:00 PM'»." yet this Field is of DateTime precision. Any suggestions or answers to why this is occuring?
var myquery= " SELECT [System.Id]" +
" FROM WorkItems " +
" WHERE " +
" [System.TeamProject] = '" + ivSettings.Project + "'" +
" AND [System.ChangedDate] = '" + ivSettings.LastSyncGen + "'" + " " +
" ORDER BY [System.Id]"
, null,false);
Query qry = new Query(myworkitemstore, myquery, mycontext, false);
ICancelableAsyncResult car = qry.BeginQuery();
WorkItemCollection items = qry.EndQuery(car);
The above is my code.
Thanks in advance
Are you sure that the following line is what you're using:
Query qry = new Query(myworkitemstore, myquery, mycontext, false);
You shouldn't get this error when the last parameter is set to false. The error should only occur when you set that parameter to true or don't supply it at all. The default is true.
Reference:
http://teamfoundation.blogspot.com/2008/01/specifying-date-and-time-in-wiql.html
Just a suggestion - have you tried doing this query in the TFS API
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://localhost:8088/tfs"));
tfs.EnsureAuthenticated();
var workItemStore = tfs.GetService<WorkItemStore>();
var query = string.Format(#" Select [Id], [Work Item Type], [Title], [State], [System.ChangedDate] From WorkItems", title);
List<WorkItem> workItems = workItemStore.Query(query)
And then doing a LINQ query on the System.Changed Date...
I haven't tried it but that could work?
I ran into the same problem while trying to query for the latest updates and worked around it by doing the following
// defined elsewhere
private DateTime lastUpdated;
string consult = "select * from WorkItem where [Created Date] > ' " + lastUpdated.ToString("MM/dd/yy") +
"' AND [Work Item Type] = 'Test Case'";
IEnumerable<ITestCase> tcc = testManagementTeamProject.TestCases.Query(consult).Where(tp => tp.DateCreated > lastUpdated);
I did something very similar for retrieving test results
I was having the same problem and Ravianth's solution worked for me. The problem might be with the date format. In my case converting the date to "yyyy-MM-dd HH:mm:ss" format worked.
i am trying to make a select statement on a datatable to get the row that is within the date range i am looking for. I am new to this an i dont quite understand how this select statement works. I tried to write this but is not working. Can you please give me a hand here. I am stuck
foundRows = dt.Select("DATE1 <= '" + date1+ "' AND DATE2 >= '" + date1+ '"');
This the Best Optimal Search Criteria I have Tested.
you having to dates.
From_Date = 12/01/2012
To_Date = 12/31/2012
and Your column in DataTable upon which you applying . (in my code 'date')
Your Select Statement will be like this.
DataRow[] rows = newTable.Select("date >= #" + from_date + "# AND date <= #" + to_date + "#");
Besides wrapping your dates with #, if date1 is a DateTime and not a string, you need to use the ToString(your date format) to get the correct sql statement. For debugging it make it easier if first you create a string containing your filter, then do the select using that string. Then you can look at the string and use that in the query builder to validate your sql.
I posted an answer on this post.
DataTable Select by exact DateTime
You can use a similar approach by using ticks to select in a range.
Using this inside an SSIS script component. I just used the example from above that included "#" around the dates. Also I converted each to string. This worked perfectly.
Just in case you want to know how I setup this up inside SSIS:
First had a data flow using the recordset destination with an Object variable to store the recordset.
in my script I included the variable as a read only.
In the main class...
public class ScriptMain : UserComponent
{
OleDbDataAdapter a = new OleDbDataAdapter();
System.Data.DataTable AwardedVacTable = new System.Data.DataTable();
...
...
then in Pre-Execute...
public override void PreExecute()
{
base.PreExecute();
a.Fill(AwardedVacTable, Variables.rsAwardedVac);
...
...
then in a custom method accessed the datatable ...
String dtFilter = "EmployeeID = " + empId.ToString() + " AND (#" + Convert.ToString(StartDate) "# <= EndDate AND #" + Convert.ToString(StartDate) + "# >= StartDate" + " OR #" + Convert.ToString(StartDate.AddDays((double)numDays)) + "# >= StartDate AND #" + Convert.ToString(StartDate.AddDays((double)numDays)) + "# <= EndDate)";
DataRow[] Overlaps = AwardedVacTable.Select(dtFilter);
expression = "Date > #2015-1-1#";
DataRow[] foundRows = table.Select(expression);
与
select * from tablename where Date>'2015-1-1'