SharePoint get current list item from a collection - sharepoint-2010

ive made a small app using c# for sp 2010, what i am doing is getting items from a collection and viewing specific fields that i want to, the problem is when i click an item it shows me the details of every item assigned to the current user, how can i show only the details of the current item which the user clicks, below is my code...thanks
foreach (SPListItem myItem in myItemCollection)
{
if (myList.Fields.ContainsField("Title"))
{
EntreeListItemDetailNameValue l = lGrp.AddListItem<EntreeListItemDetailNameValue>();
SPField myField1 = myList.Fields.GetField("Title");
l.Name = myField1.Title;
try
{
l.Value = myField1.GetFieldValueAsText(myItem["Title"]);
}
catch
{
l.Value = "";
}
}
if (myList.Fields.ContainsField("Priority"))
{
EntreeListItemDetailNameValue l2 = lGrp.AddListItem<EntreeListItemDetailNameValue>();
SPField myField = myList.Fields.GetField("Priority");
l2.Name = myField.Title;
try
{
l2.Value = myField.GetFieldValueAsText(myItem["Priority"]);
}
catch
{
l2.Value = "";
}

You could use GetItemById()
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitemcollection.getitembyid.aspx
void list_Click(object sender, EventArgs e) {
int clickedid = 0; //get the id from the clicked item
ShowForm(); //show detail form
DataBind(clickedid); //databind detail form
}
void DataBind(int id) {
SPListItemCollection myItemCollection = showthing; //load the list items, query using SPQuery, or SPList.Items
SPListItem item = myItemCollection.GetItemById(id);
form.Title = item["Title"];
}

Related

how to over come System out memory exception in windows phone 8?

I'm Developing windows phone 8 application.
In my application i'm using listbox.I bind listbox value form Webservice. Webservice return json format data's.
The webservice return 40 to 50 records.I bind all the values into listbox.
Everthing work fine.Only on first time run.
For example:-
My project page structure.
1.welcomepage
2.Menu Page (it contain six buttons. click on any one particular button it's redirect to sub-menupage)
3.Sub-menupage(Six different page present)
In menu page Hotels button is present . if hotels button is clicked it's navigate to Hotels Page.
Now my problem is:-
First Time - welcomepage -> Menu Page -> HotelSubmenu [List of hotels is bind in listbox from webservice]
Now I goback to Menupage by click on hardwareback button.Now it's in Menu page
If i click again the same Hotels button
It show me the error
e.ExceptionObject {system.OutofMemoryException:Insufficient memory to continue the execution of the program.
[System.outofmemoryException]
Data {system.Collections.ListDictionaryInternal}
HelpLink null
Hresult -2147024882
Message "insufficient memory to continue the execution of the program"
My C# code for bind values in listbox
public void commonbind()
{
try
{
this.loadimg.Visibility = System.Windows.Visibility.Visible;
loadcheck();
string common_url = "http://xxxxxx.com/Service/bussinesscitynamesub.php?bcatid=" + businessid + "&cityname=" + cityname + "&bsubid=" + filterid;
WebClient common_wc = new WebClient();
common_wc.DownloadStringAsync(new Uri(common_url), UriKind.Relative);
common_wc.DownloadStringCompleted += common_wc_DownloadStringCompleted;
}
catch (Exception ex)
{
}
}
void common_wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
lbbusiness.Items.Clear();
var common_val = e.Result;
if (common_val != "null\n\n\n\n")
{
lbopen = 2;
var jsonconvertvalue = JsonConvert.DeserializeObject<List<common_bindclass>>(common_val);
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
this.loadimg.Visibility = System.Windows.Visibility.Collapsed;
loadcheck();
}
else
{
if (lbopen == 0)
{
MessageBoxResult resultmsg = MessageBox.Show("No Result present based on your current Location! " + System.Environment.NewLine + "Now showing result without Location based", "Sorry!", MessageBoxButton.OK);
if (resultmsg == MessageBoxResult.OK)
{
lbbusiness.Items.Clear();
cityname = "";
**commonbind();**
}
else
{
NavigationService.GoBack();
}
}
else if (lbopen == 1)
{
MessageBox.Show("No Result Present In this Categories");
LPfilter.Open();
}
else if (lbopen == 2)
{
MessageBox.Show("No Result Present In this City");
Lpcity.Open();
}
}
}
catch (Exception ex)
{
}
}
I try with following method for solve the memory exception
Try1:-
Clear the List box value before bind every time.
Try2:-
Create the new list every time
common_bindclass bind = new common_bindclass();
foreach (common_bindclass bind in jsonconvertvalue)
{
lbbusiness.Items.Add(bind);
}
I change the above code to
List<common_bindclass> ls = new List<common_bindclass>();
ls = jsonconvertvalue;
for (int i = 0; i < ls.Count; i++)
{
lbbusiness.Items.Add(ls[i]);
}
MY Output For single List
But my try's not help for me .
any one tell me how to solve it. or alternate way .
How to find in which line the error occur .[I try with break point but it's not help me]

Razor MVC return HTML

I tried to research a bit, but has not found a proper solution to this.
What I'm trying to do is to have a HTML.Action in a page like so
Html.Action("Calendar", "GlobalShared")
Inside the action "Calendar", I need to return the result of the html of the traditional calendar control
public ActionResult Calendar(
String ID,
String CssClass,
int CellSpacing,
int CellPadding,
String BorderWidth,
String ShowGridLines,
String ShowTitle,
String DayNameFormat
)
{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
}
How can I do this? Btw, I use HTML.Action is because I read that it returns a html string, is that correct or should I be doing some other ways?
Thanks
Edit. Before I attempted this in a controller, I tried the following code in a view .cshtml and it works, but I prefer to move the code into a controller
#{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
cal.RenderControl(new HtmlTextWriter(Html.ViewContext.Writer));
}
Edit #2. The reason I want to use that in a controller is because if in the future, i want to hook up an event say "DayRender", I can do it in the controller. I can not do the same in a view without polluting the view page.
Okay. Thanks guys. I figured out. Basically, I need to use #{Html.RenderAction(..)} and in the action itself, use StringBuilder/StringWriter and then return Content(...). Code below
In View
#{Html.RenderAction("Calendar", "GlobalShared");}
In Controller
[ChildActionOnly]
public ActionResult Calendar(
)
{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
cal.DayRender += new System.Web.UI.WebControls.DayRenderEventHandler(CalendarDayRender);
StringBuilder sb = new StringBuilder();
using (System.IO.StringWriter sw = new System.IO.StringWriter(sb))
{
System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(sw);
cal.RenderControl(writer);
}
String calHTML = sb.ToString();
return Content(calHTML);
}
private void CalendarDayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
e.Cell.Text = "";
if (e.Day.Date == System.DateTime.Today)
{
e.Cell.CssClass = "today";
System.Web.UI.HtmlControls.HtmlGenericControl h3 = new System.Web.UI.HtmlControls.HtmlGenericControl("h3");
h3.InnerHtml = HttpContext.GetGlobalResourceObject("JTG_DateTime", "JTK_Today") + " " + e.Day.DayNumberText;
e.Cell.Controls.Add(h3);
}
}
Simply move your code
#{
System.Web.UI.WebControls.Calendar cal = new System.Web.UI.WebControls.Calendar();
cal.ID = "MyCalendar";
cal.CssClass = "month-view";
cal.CellSpacing = 0;
cal.CellPadding = -1;
cal.BorderWidth = 0;
cal.ShowGridLines = false;
cal.ShowTitle = false;
cal.DayNameFormat = System.Web.UI.WebControls.DayNameFormat.Full;
cal.RenderControl(new HtmlTextWriter(Html.ViewContext.Writer));
}
in a view and return that View from your Calendar Action.
public ActionResult Calendar(
String ID,
String CssClass,
int CellSpacing,
int CellPadding,
String BorderWidth,
String ShowGridLines,
String ShowTitle,
String DayNameFormat
)
{
return View("Calendar");
}
You can either create a ViewModel or use ViewBag to transfer these values from Calendar Action to your newly created View

how to Edit a Sharepoint Calendar event Item on event Click in SPCalendarView control

I have created a custom Calendar, using the <SharePoint:SPCalendarView id=spcalView runat="server"> </SharePoint:SPCalendarView>.
Then I had inserted some events to the Calendar List, and its possible for me to display the events in the view spcalView created above. For this I passed SPListItemCollection(ie retrieved the collection from Calendar List) to a function MakeSchedule().
private SPCalendarItemCollection MakeSchedule(SPListItemCollection calListItems)
{
SPCalendarItemCollection items = new SPCalendarItemCollection();
for (int i = 0; i < calListItems.Count; i++)
{
SPListItem item = calListItems[i];
DateTime StartTime = Convert.ToDateTime(item["EventDate"]);
DateTime EndTime = Convert.ToDateTime(item["EndDate"]);
string appointmentId = "";
if (item["AppointmentID"] != null)
appointmentId = item["AppointmentID"].ToString();
string clientID = "";
if (item["clientID"] != null)
clientID = item["clientID"].ToString();
string Description = "";
if (item["Description"] != null)
Description = item["Description"].ToString();
string Location = "";
if (item["Location"] != null)
Location = item["Location"].ToString();
string Title = "";
if (item["Title"] != null)
Title = item["Title"].ToString();
bool Recurrance = false;
if (item["fRecurrence"] != null)
Recurrance = (bool)item["fRecurrence"];
bool AllDayEvent = false;
if (item["fAllDayEvent"] != null)
AllDayEvent = (bool)item["fAllDayEvent"];
SPWeb web = SPContext.Current.Web;
string relativeURL = web.ServerRelativeUrl;
string absoluteURL = web.Url;
items.Add(
new SPCalendarItem()
{
ItemID = item["ID"].ToString(),
StartDate = StartTime,
EndDate = EndTime,
hasEndDate = true,
Title = Title,
Location = Location,
Description = Description,
IsAllDayEvent = AllDayEvent,
IsRecurrence = Recurrance,
CalendarType = (int)SPCalendarType.Gregorian,
BackgroundColorClassName="ApptCnfirmed",
DisplayFormUrl = relativeURL + "/_layouts/TestProj.Webparts/AppointmentsEdit.aspx"
}
);
}
return items;
}
Here in this for each event item added to the SPCalendarItemCollection, i had set the DisplayFormUrl to an application page. So when i click an event in Spcalendar view,it gets redirected to application page along with the ID of the item clicked as query string.
In the Application page, retrieved the ID, and based on the ID, I retrieved the currentLstItem. but from that i am not able to get the custom fields added by me in the CalendarList.
public partial class AppointmentsEdit : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
string ID = Page.Request.QueryString["ID"].ToString();//this Id is the unique id of the Appointment List
string Source=Page.Request.QueryString["Source"].ToString();
if (ID != "" && ID != null)
{
SPList lstApp = SPContext.Current.Web.Lists["Appointment"];
SPListItem currentLstItem = lstApp.GetItemById(Convert.ToInt32(ID.ToString()));
}
else
{
}
}
}
Is this the proper way to edit the calendar event?, because i have custom fields added to the Calendar List in sharepoint. I tried using designer but i am not able to get the code behind for the EditForm.aspx.
Thanks in advance!!

Adding category to new mails

I am creating a VSTO 2007 Addin using COM. My requirement is to mark all the new mails into Blue category. I have the following code in OnNewMailEx handler
HRESULT hrGetNewMail;
_NameSpacePtr pMAPI = NULL;
hrGetNewMail = spApp->GetNamespace((_bstr_t)GetStringFromTable(147),&pMAPI);
if(FAILED(hrGetNewMail))
{
if(spApp!=NULL)
spApp.Release ();
return OPERATION_FAILED;
}
if(spApp!=NULL)
spApp.Release ();
CComBSTR EntryStoreID;
MAPIFolderPtr spMAPIFolder = NULL;
hrGetNewMail = pMAPI->GetDefaultFolder (olFolderInbox, &spMAPIFolder);
if(FAILED(hrGetNewMail))
{
if(pMAPI!=NULL)
pMAPI.Release ();
return OPERATION_FAILED;
}
hrGetNewMail = spMAPIFolder->get_StoreID (&EntryStoreID);
if(FAILED(hrGetNewMail))
{
if(spMAPIFolder!=NULL)
spMAPIFolder.Release ();
if(pMAPI!=NULL)
pMAPI.Release ();
}
if(spMAPIFolder!=NULL)
spMAPIFolder.Release ();
VARIANT varEntryStoreID;
hrGetNewMail = EntryStoreID.CopyTo (&varEntryStoreID);
if(FAILED(hrGetNewMail))
{
return OPERATION_FAILED;
}
IDispatch* spLatestMailitem;
hrGetNewMail = pMAPI->GetItemFromID (EntryID,varEntryStoreID,&spLatestMailitem);
if(FAILED(hrGetNewMail))
{
if(pMAPI!=NULL)
pMAPI.Release ();
}
if(pMAPI!=NULL)
pMAPI.Release ();
CComQIPtr <Outlook::_MailItem> spMailItem;
hrGetNewMail=spLatestMailitem->QueryInterface(&spMailItem);
HRESULT hrCat = spMailItem->put_Categories(_T("Blue Category"));
//spMailItem->put_FlagIcon(olRedFlagIcon);
hrCat = spMailItem->Save();
after execution when i open the new mails it is showing the category as Blue but in the inbox it is not marked in any category. When i close and open the outlook the category is gone even when i open the mail which was earlier marked as blue category. however i could add a flag which is there whenever i close and open the outlook. please suggest me the problem
If the category does not exist in the master category list I don't think it keeps it. To add a category to the master category list. See for more information http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.categories.aspx
Also you example will overwrite any existing categories. you should check if a category is already specified and if so seperate the existing value and value you wish to add with a comma.
var existingCategories = item.Categories;
if (string.IsNullOrWhiteSpace(existingCategories))
{
item.Categories = "MyCategory";
}
else
{
if (item.Categories.Contains("MyCategory") == false)
{
item.Categories = existingCategories + ", MyCategory";
}
}
item.Save();

Error in DataGrid random behavior when scrolling in Silverlight 4.0

I have a datagrid and its rows are colored based on certain condtions..There is a vertical scrollbar for my datagrid.. If the user scrolls the datagrid the index of the colored rows r getting changed.. For eg: if 2 row is colored if the user scrolls down and comes up the index of the colored row is getting messed up...
here is the code....
dggeneralconfiguration.LoadingRow += new EventHandler<DataGridRowEventArgs>(grid1_LoadingRow);
dggeneralconfiguration.UnloadingRow += new EventHandler<DataGridRowEventArgs>(grid1_UnloadingRow);
void grid1_LoadingRow(object sender, DataGridRowEventArgs e)
{
ShowGeneralGrid c = e.Row.DataContext as ShowGeneralGrid;
if (c.Status == false)
{
if (e.Row != null)
{
e.Row.Background = new SolidColorBrush(Colors.Red);
//e.Row.Background = new SolidColorBrush(Colors.Transparent);
}
}
}
void grid1_UnloadingRow(object sender, DataGridRowEventArgs e)
{
ShowGeneralGrid c = e.Row.DataContext as ShowGeneralGrid;
if (c.Status == false)
{
if (e.Row != null)
{
e.Row.Background = new SolidColorBrush(Colors.Red);
//e.Row.Background = new SolidColorBrush(Colors.Transparent);
}
}
}
Better late than never. ;-) . I too had similar kind of problem.. try assigning row background to null on unloading row event.
private void dg_UnloadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Background = null;
}