I'm using C# and I get data from database like this:
da.SelectCommand = new SqlCommand("SELECT name,company,startdate,enddate,DATEDIFF(day,GETDATE(),enddate) AS days FROM Person", cn);
ds.Clear();
da.Fill(ds);
dgvViolation.DataSource = ds.Tables[0];
and the data will dispaly in datagridview like this :
name company startdate enddate days
---------------------------------------
john IBM 12/2/2012 20/2/2012 5
steven IBM 1/2/2012 12/2/2012 -3
I need the datagridview to display the positive values that appear in the days columns only. How do I do this?
Change the query to
"SELECT name,company,startdate,enddate,DATEDIFF(day,GETDATE(),enddate) AS days FROM Person WHERE days > 0"
Why don't you just change your SQL command to return the values above 0?
But if you want to do it with all the data returned, you can use the RowDataBound event of the gridview, something like this:
protected void gridview_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
//look at the value of the days column and use e.Row.Style["Display"] = "none"; to hide it.
}
}
Related
I've added the Excel upload feature to the Details section of the Employee Time Card screen (EP305000). This works fine, but if the 'Time' field (which is actually date_time, but I can't find that in the DAC - only 'Date') isn't specified in the upload, it defaults to midnight (12:00 AM). I want this to default to 8:00 AM, but I'm not sure how to do this, since the field is actually a date. It doesn't seem like I can just use [PXDefault] or anything simple like that.
How can I accomplish this?
Thanks...
Here's the solution I came up with, using the 'RowInserted' event:
protected void EPTimeCardDetail_RowInserted(PXCache sender, PXRowInsertedEventArgs e)
{
var eptcd = (EPTimecardDetail)e.Row;
DateTime theDate = (DateTime)eptcd.Date;
DateTime MyDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, 8, 0, 0);
eptcd.Date = MyDate;
}
I have a set of text files that I am reading into a datatable. I want to be able to read the frist column (Id) and find out the highest number. Each of the files goes from 0 to at least 21 sequentially. I tried suggestions from the following link: How to select min and max values of a column in a datatable?
Sadly, I could not any to work. The one suggestion that kind of worked is shown in the second last line, but it returns a value of 8 or 9. Any suggestions as to how to properly get the results I am looking for?
string filePath = System.IO.Path.GetFullPath(curriculum);
DataTable curriculmDataTable = new DataTable();
curriculmDataTable.Columns.Add("Id");
curriculmDataTable.Columns.Add("Course");
curriculmDataTable.Columns.Add("Credit");
// Read in a file line-by-line, and store it
var txtFileLine = File.ReadAllLines(filePath).ToList();
//Reads line splits data to colums at tab (ASCII value 9)
txtFileLine.ForEach(line => curriculmDataTable.Rows.Add(line.Split((char)9)));
//Suggestions from link
int max = Convert.ToInt32(curriculmDataTable.Select("Id=max(Id)")[0][0]);
label1.Text = ""+ max;
The problem is that you have created string columns but you want to get the max-values according to their numeric value. The best way is to store the corrrect type in the first place. Then you could either use DataTable.Compute or Linq-To-DataSet:
create an int column:
curriculmDataTable.Columns.Add("Id", typeof(int));
convert the strings to int and add them to the table:
foreach(string line in File.ReadLines(filePath))
{
DataRow row = curriculmDataTable.Rows.Add();
string[] fields = line.Split(new[]{(char)9});
int id;
if(fields.Length == 3 && int.TryParse(fields[0], out id)
{
row.SetField("Id", id);
row.SetField("Course", fields[1]);
row.SetField("Credit", fields[2]);
}
}
Now you can use Linq:
int maxID = curriculmDataTable.AsEnumerable().Max(r => r.Field<int>("Id"));
DataTable.Compute (works also with earlier .NET versions):
int maxID = (int)curriculmDataTable.Compute("Max(Id)", "")
We can get max value from the column in a dataTable using this syntax
var maxValue = dataTblDetails.Compute("max(ColumnName)", string.Empty);
Background:
The company I work for has a regular SharePoint list with a custom ContentType (that does not inherit from a calendar list item) that it uses for Events. It then shows these using a calendar view. Seems simple enough.
We have the need to allow the user to choose a timezone for the event (different from their regional setting) that they are adding and to add the information to sharepoint such that it will show the correct time for each user looking at it world wide (based on their regional setting of course).
I added a list to SharePoint that is used to lookup SystemTimeZones (basically a SharePoint List representation of TimeZoneInfo.GetSystemTimeZones())
SPList timeZonesList = thisWeb.Lists.TryGetList("SystemTimeZones");
if(timeZonesList == null)
{
string title = "SystemTimeZones";
string description = "SharePoint List representation of TimeZoneInfo.GetSystemTimeZones() used for lookup.";
Guid newListId = thisWeb.Lists.Add(title, description, SPListTemplateType.GenericList);
timeZonesList = thisWeb.Lists.GetList(newListId, true);
timeZonesList.Fields.Add("SystemTimeZoneId", SPFieldType.Text, true);
timeZonesList.Fields.Add("SystemTimeZoneName", SPFieldType.Text, true);
SPView defaultTimeZonesView = timeZonesList.DefaultView;
defaultTimeZonesView.ViewFields.Add("SystemTimeZoneId");
defaultTimeZonesView.ViewFields.Add("SystemTimeZoneName");
defaultTimeZonesView.Update();
foreach (TimeZoneInfo timeZone in TimeZoneInfo.GetSystemTimeZones())
{
SPListItem temp = timeZonesList.AddItem();
temp["SystemTimeZoneId"] = timeZone.Id;
temp["SystemTimeZoneName"] = timeZone.DisplayName;
temp.Update();
}
}
I'm using this list for the lookup item for EventTimeZone in my custom add and edit forms for this list. The forms are direct copies of what SharePoint Designer would create (in that they are using the SharePoint:FormField's) they are just in Visual Studio bc I needed code-behind. I wanted to allow the users to see the events in their Regional TimeZone however when they edit them I wanted to show them in the TimeZone they were entered. (IE my regional timezone is Central so when I look at a Mountain meeting it will show me 10-11am but when I edit that same meeting it will say it is 9-10am). So on page load of edit I adjust the times:
SPListItem thisEvent = eventsList.GetItemById(savebutton1.ItemId);
if (thisEvent != null)
{
bool isAllDayEvent = false;
if (thisEvent["fAllDayEvent"] != null)
{
isAllDayEvent = (bool)thisEvent["fAllDayEvent"];
}
if (!isAllDayEvent)
{
SPFieldLookupValue lookupValue = new SPFieldLookupValue(thisEvent["Event Time Zone"].ToString());
TimeZoneInfo eventTimeZone = GetEventTimeZoneByListItemId(lookupValue.LookupId, rootWeb);
SPTimeZone regionalTimeZone = GetRegionalTimeZone(rootWeb);
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
DateTime originalStartDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalStartDateTime), eventTimeZone);
ff3.ListItemFieldValue = originalStartDateTime;
DateTime regionalEndDateTime = Convert.ToDateTime(thisEvent["EndDate"]);
DateTime originalEndDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalEndDateTime), eventTimeZone);
ff4.ListItemFieldValue = originalEndDateTime;
}
else
{
// for some reason with all day events, sharepoint saves them
// as the previous day 6pm. but when they show up to any user
// they will show as 12am to 1159pm and show up correctly on the calendar
// HOWEVER, when it comes to edit, the start date isn't corrected on the
// form, so continuing to save without fixing it will continue to decrease
// the start date/time by one day
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
ff3.ListItemFieldValue = regionalStartDateTime.AddDays(1);
}
All day events were strange but I was able to make it work by just writing test cases and see what happened (as you can see from my comments).
Then I tie into the list event receivers ItemAdded and ItemUpdated to "fix" the times since SharePoint is going to save them based on the user's regional setting and not the timezone the user chose. (Of course I'm slightly new to SharePoint -- not c# -- so I may have very much over complicated this, but I have been able to fine little documentation online). In the end I end up setting:
addedItem["StartDate"] = regionalTimeZone.UTCToLocalTime(correctedEventStart.ToUniversalTime());
addedItem["EndDate"] = regionalTimeZone.UTCToLocalTime(correctedEventEnd.ToUniversalTime()); TADA!! It saves and display perfectly! I was so excited! Until... I tried to save a recurring event. All of my recurring events save wonderfully, it's not the recurring part that's messed up. For some reason, after I change the StartDate and EndDate on a recurring event and call addedItem.Update() it is recalculating the "Duration" as if it is a single even instead of a recurring event. Example: I have an event that happens for a week daily from 9-10. When I first enter ItemAdded my Duration is 3600 (1 hour) as it should be bc Duration is treated differently for recurring events. However after I adjust the times and call Update() the duration spans the entire week :( If I manually set the Duration:
if (isRecurrence)
{
addedItem["Duration"] = (correctedEventEnd.TimeOfDay - correctedEventStart.TimeOfDay).TotalSeconds;
}
It still gets reset on Update(). So when you view the recurring item in a Calendar View the item spans the entire week instead of showing once a day.
I have all but pulled my hair out trying to figure this out. Any guidance would be wonderful. I understand Duration is a calculated field but I can't understand why calling listItem.Update() would ignore the fact that it is indeed properly marked as a recurring event and not calculate the Duration correctly. This honestly seems like a bug with SP 2010.
Thanks in advance!
**
EDIT: Additional info after comments below...
**
This SharePoint env has a server in pacific time and users across all US TimeZones, London, Tokyo, Abu Dabi, etc. Users in one timezone need to be able to create events in other timezones. Since nothing in the user's profile (for us anyway) will tell us what timezone they would like to see everything in, we added code to our master page to look at the local machine's timezone and always set their regional setting accordingly.
Example: I am in Nashville and I want to create an event that will happen in LA:
The data in ItemAdded shows that StartDate is what I entered 9am. So I'm creating a date that has PST at the end of it:
DateTime correctedEventStart = DateTime.Parse(addedItem["StartDate"] + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
DateTime correctedEventEnd = DateTime.Parse(addedItem["EndDate"] + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
Then to "trick" SharePoint I'm converting that PST time into the users regional time (so the user doesn't have to know anything about their regional setting nor do they have to think). So 9am PST is 7am CST (bc that's what SharePoint expects the time to be in since that's my regional setting). Here's the converstion from the correct time+timezone to the user regional timezone:
addedItem["StartDate"] = regionalTimeZone.UTCToLocalTime(correctedEventStart.ToUniversalTime());
addedItem["EndDate"] = regionalTimeZone.UTCToLocalTime(correctedEventEnd.ToUniversalTime());
I don't know if this makes sense to anyone outside of my world. But SharePoint obviously expects the times to be in the user's regional (or the web's) timezone. That's obvious my from unit testing. If there is an OOB way for me to allow a user in Central Time to create a meeting from 9-10am Pacific Time in a custom list I would LOVE to be able to use that. But I haven't been able to find anything.
Again, all of this works great... until you come to Recurring Events. And actually it works for recurring events until you try to view said event in a Calendar View. Then it looks like this:
Notice that "Recurring 8" is recurring the way it's supposed to, daily for 2 instances. However, the "span" or "duration" of the recurrence is 2 days rather than 1 hour. Where as "Recurring 15" shows correctly. The only difference in field values between the two when output to debug is the "Duration" field. Recurring 8 had it's start and end date's updated in ItemAdded and Recurring 15 went through ItemAdded but the ListItem.Update() was commented out. Per documentation SharePoint is supposed to calculate Duration differently for recurring items than it does for single items. The fact that the start and end dates are changed using the object model should not negate that.
Ok, so the way I ended up handling this is as follows. I decided to back out of the list event receiver because it really does appear to be a SharePoint bug in the recalculation of Duration for recurring events now working correctly. I opted to tie into the save event on the form and changing the values before they are even sent. This seems to work so far in all scenarios. All of my math is the same as before. So in my New2.aspx (new item form for this list)
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if ((SPContext.Current.FormContext.FormMode == SPControlMode.New) || (SPContext.Current.FormContext.FormMode == SPControlMode.Edit))
{
SPContext.Current.FormContext.OnSaveHandler += new EventHandler(SaveHandler);
}
}
protected void SaveHandler(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
// fix times
SPFieldLookupValue lookupValue = new SPFieldLookupValue(ff5.Value.ToString());
TimeZoneInfo eventTimeZone = GetEventTimeZoneByListItemId(lookupValue.LookupId, SPContext.Current.Web);
SPTimeZone regionalTimeZone = GetRegionalTimeZone(SPContext.Current.Web);
bool isAllDayEvent = Convert.ToBoolean(ff6.Value);
bool isRecurrence = Convert.ToBoolean(ff11.Value);
DateTime correctedEventStart = DateTime.MinValue;
DateTime correctedEventEnd = DateTime.MinValue;
if (!isAllDayEvent && eventTimeZone != null && regionalTimeZone != null)
{
correctedEventStart = DateTime.Parse(ff3.Value.ToString() + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
correctedEventEnd = DateTime.Parse(ff4.Value.ToString() + " " + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Hours + ":" + eventTimeZone.GetUtcOffset(DateTime.UtcNow).Minutes);
ff3.ItemFieldValue = regionalTimeZone.UTCToLocalTime(correctedEventStart.ToUniversalTime());
ff4.ItemFieldValue = regionalTimeZone.UTCToLocalTime(correctedEventEnd.ToUniversalTime());
}
SPContext.Current.ListItem.Update();
}
}
This updates the times as my previous approach does but it will also calculate the duration correctly.
SharePoint handles displaying the correct time based on the user's regional settings (or web if the user hasn't set it) and displaying the correct times in calendar views. I did have to change the Edit form to have the correct values on edit:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
using (SPWeb rootWeb = SPContext.Current.Site.RootWeb)
{
SPList eventsList = rootWeb.Lists.TryGetList("Events");
if (eventsList != null)
{
SPListItem thisEvent = eventsList.GetItemById(savebutton1.ItemId);
if (thisEvent != null)
{
bool isAllDayEvent = false;
if (thisEvent["fAllDayEvent"] != null)
{
isAllDayEvent = (bool)thisEvent["fAllDayEvent"];
}
if (!isAllDayEvent)
{
SPFieldLookupValue lookupValue = new SPFieldLookupValue(thisEvent["Event Time Zone"].ToString());
TimeZoneInfo eventTimeZone = GetEventTimeZoneByListItemId(lookupValue.LookupId, rootWeb);
SPTimeZone regionalTimeZone = GetRegionalTimeZone(rootWeb);
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
DateTime originalStartDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalStartDateTime), eventTimeZone);
ff3.ListItemFieldValue = originalStartDateTime;
DateTime regionalEndDateTime = Convert.ToDateTime(thisEvent["EndDate"]);
DateTime originalEndDateTime = TimeZoneInfo.ConvertTimeFromUtc(regionalTimeZone.LocalTimeToUTC(regionalEndDateTime), eventTimeZone);
ff4.ListItemFieldValue = originalEndDateTime;
}
else
{
// for some reason with all day events, sharepoint saves them
// as the previous day 6pm. but when they show up to any user
// they will show as 12am to 1159pm and show up correctly on the calendar
// HOWEVER, when it comes to edit, the start date isn't corrected on the
// form, so continuing to save without fixing it will continue to decrease
// the start date/time by one day
DateTime regionalStartDateTime = Convert.ToDateTime(thisEvent["StartDate"]);
ff3.ListItemFieldValue = regionalStartDateTime.AddDays(1);
}
}
}
}
}
catch (Exception ex)
{
DebugLogger.WriteLine(ex);
}
}
}
The Edit form has the same OnInit and SaveHandler as New.
I think you are running afoul of the shennagins that SharePoint uses for reccuring events. Essentially the events are stored in a single list item and expanded at query time. This makes the storage of events quite counter intuitive to how you expect.
From that post it looks like the EventDate and EndDate fields are used differently depending on the recurrence or not.
Also be aware the SharePoint stores dates in UTC 'under the hood' and converts back to the users (or websites) timezone on display. You may be able to use this knowledge to optimise some of the date logic.
More information
http://fatalfrenchy.wordpress.com/2010/07/16/sharepoint-recurrence-data-schema/
Share point 2010 ItemAdding insert Recurrence data on calendar
http://blog.tylerholmes.com/2012/02/how-sharepoint-deals-with-time-and-time.html
Here is the code I used to create an occuring event in another timezone (note: I did not explicitly set the duration)
public void AddRecurringItemGTM8Perth(SPList list)
{
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><windowEnd>2013-02-20T01:00:00Z</windowEnd></rule></recurrence>";
SPListItem newitem = list.Items.Add();
newitem["Title"] = "Perth " + DateTime.Now.ToString();
newitem["RecurrenceData"] = recData;
newitem["EventType"] = 1;
DateTime correctedEventStart = new DateTime(2013, 2, 3, 12, 0, 0);
//note that date is end of event and time is event end to calculate duration
DateTime correctedEventEnd = new DateTime(2013, 2, 20, 13, 0, 0);
SPTimeZone spTz = SPRegionalSettings.GlobalTimeZones[74]; //perth
correctedEventStart = spTz.LocalTimeToUTC(correctedEventStart);
correctedEventEnd = spTz.LocalTimeToUTC(correctedEventEnd);
correctedEventStart = list.ParentWeb.RegionalSettings.TimeZone.UTCToLocalTime(correctedEventStart);
correctedEventEnd = list.ParentWeb.RegionalSettings.TimeZone.UTCToLocalTime(correctedEventEnd);
newitem["Start Time"] = correctedEventStart;
newitem["End Time"] = correctedEventEnd;
newitem["Recurrence"] = true;
newitem["fAllDayEvent"] = false;
newitem["WorkspaceLink"] = false;
newitem["UID"] = Guid.NewGuid();
newitem.Update();
list.Update();
}
So I convert from users "local" to UTC and then back to the web local.
The UID is necessary or there is an error when you click on the event.
If you want a recurrence of 13 say... the code is:
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><repeatInstances>13</repeatInstances></rule></recurrence>";
DateTime correctedEventEnd = new DateTime(2013, 2, 3, 13, 0, 0).AddDays(13);
Whereas no end date is :
string recData = "<recurrence><rule><firstDayOfWeek>su</firstDayOfWeek><repeat><daily dayFrequency=\"1\" /></repeat><repeatForever>FALSE</repeatForever></rule></recurrence>";
DateTime correctedEventEnd = new DateTime(2013, 2, 3, 13, 0, 0).AddDays(998);
It might be quite old, but my answer may help someone.
You just have to explicitly put EventType = 1 in update as well.
I have one datasheet like mentioned below
WorkWeek Person1 Person2
WW1 X Y
WW2 Z A
WW3 X Z
Where A,X,Y & Z are members of the sharepoint group.
Required I want display a webpart like this
WW1
Image1 Image2
X Y
Next Week the webpart should get updated like this dynamically.
WW2
Image3 Image4
Z A
Where this requirement is possible, If possible then pls suggest how to accomplish this.
I can provide you some Logic which may help you to accomplish this requirement.
Create one Visual web part with the user control which has html as per your requirement,
To get the data from the datasheet use the Code to read the data from Data sheet
When you want to display the data for the First week create one varible and maintain it to identify the sequence of week to get from datasheet.
First time When you access the datasheet set this varibale with your week of year number.
Condition the reading of datasheet with this variable like IF variable is null then assign it the week no of year.,
Check this variable next time you come to this logic that If variable is less than the week no current week no of year then take datasheet last you get + 1 means Datasheet 2 and so on
..
Sorry for bad english
variable : one for DaasheetNo, WeekNo,CurrentWeekNo
assign datasheetNo = Sheet1
If(WeekNo== Null)
{
first time getdata from DaasheetNo (First Sheet)
}
else if(WeekNo < CurrentWeekNo)
{
Get data from datasheetNo +1
}
Hope it helps you
This is called weekly update Webpart in SharePoint.
My Idea:
you can set one CurrentDate value like DateTime.Today to Current Web properties.also set one more properties which WorkWeek users. now check
SPWeb web = SPContext.Current.Web;
if (string.isnullorEmpty(web.Properties["CurrentDate"]))
{
web.Properties["CurrentDate"] = DateTime.Today.Tostring();
// do the stuff for displying data.
}
else
{
if(IFChangeNeeded())
{
// do the stuff for displying data.
}
else
{
web.Properties["CurrentDate"] = DateTime.Today.Tostring();
// do the stuff for displying data.
}
}
IfChangeNeeded() is function which return bool value. this function check that employee need to change on this week.
public bool IFChangeNeeded()
{
DateTime PropDate = Convert.ToDateTime(web.Properties["CurrentDate"]);
DateTime TDate = DateTime.Today;
if(WeekNo(TDate) == WeekNo(PropDate)) // WeekNo is function return weekno from current date.
{
return true;
}
else
{
return false;
}
}
I have asp.net application and am using Entity Framework to connect it with the database. in this application, I have a textbox to get the date(am using calender css style here), and its in the string type.
I have a column in my database and its in Date Time format, I need to compare the textbox value with the date column in my database, for this I just used the code as
public StudentAttendances(string date)
{
if (date != "")
{
DateTime date1 = Convert.ToDateTime(date);
foreach (DataAccess.StudentAttendance studentAttendance in buDataEntities.StudentAttendances.Where(s => s.Date == date1))
{
this.Add(new StudentAttendance(studentAttendance.StudentId));
}
}
}
for example if I select a date in my textbox(the format is 04/05/2012) and when I compare this with the database its not showing any data, but actually some datas are there for this date.
Your code is comparing both day and time (hours, minutes etc will have to match). Try comparing just the day part like this:
buDataEntities.StudentAttendances.Where(s => s.Date.Subtract(date1).Days == 0)
I also think that you should specify what format the input date from the users is in.
04/05/2012 may mean both 4th April or 5th of May depending on your computers regional setting.
Here is an example (below) for converting a date string in American format to DateTime object:
DateTime date1 = DateTime.Parse(date, new CultureInfo("en-US"));
Hope that helps!
your ask is very limited, but try to see this
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
Please check whether the following works for you:
public StudentAttendances(string date)
{
if (date != "")
{
// please see the change from your given code
DateTime date1 = DateTime.ParseExact(date, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
foreach (DataAccess.StudentAttendance studentAttendance in buDataEntities.StudentAttendances.Where(s => s.Date == date1))
{
this.Add(new StudentAttendance(studentAttendance.StudentId));
}
}
}