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

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!!

Related

Read Data attributes or Custom Attributes in SQL server from string

I want in SQL prepared dynamic query based on the shortcode.
For Eg.
DECLARE #ShortCode VARCHAR(MAX)
SET #ShortCode = '[User data="Name" data="MobileNumber"]';
User = table name
Name = User table field
MobileNumber = User table field
Query output be like
SELECT [Name],[MobileNumber] FROM [dbo].[User]
SET #ShortCode = '[Country data="Name" ID="1"]';
Country = table name
Name = Country table field
ID = User table field
Query output be like
SELECT [Name] FROM [dbo].[Country] WHERE [ID] = 1
How to extract all data attributes values and how to get User in the []
This functionality is done in C#
Here My c# code
// Model class
public class ShortCodeResult
{
public Guid? ID { get; set; }
public string TableName { get; set; }
public bool IsValidShortCode { get; set; }
public string Message { get; set; }
public Dictionary<string,object> KeyValue { get; set; }
public ShortCodeResult() {
KeyValue = new Dictionary<string, object>();
ID = Guid.NewGuid();
}
}
//Regex Filter
public class RegexFilter
{
private string oPattern = #"(\w+)=[\""]([a-zA-Z0-9_.:\""]+)";
public ShortCodeResult GetShortCodeValues(string Code)
{
var oShortCodeModel = new ShortCodeResult();
var oRegex = new Regex(oPattern, RegexOptions.IgnoreCase);
var oTableNameRegex = Regex.Match(Code, #"\b[A-Za-z]+\b", RegexOptions.Singleline).Value;
var lstMatchCollection = oRegex.Matches(Code).Cast<Match>().Where(x=>x.Value.StartsWith("data")).ToList();
if (lstMatchCollection != null && lstMatchCollection.Count > 0)
{
for (int i = 0; i < lstMatchCollection.Count; i++)
{
var oSelected = new Regex("[^=]+$").Match(Convert.ToString(lstMatchCollection[i]));
if (oSelected != null)
{
oShortCodeModel.KeyValue.Add(i.ToString(), oSelected.Value.Trim('"'));
}
}
}
oShortCodeModel.TableName = oTableNameRegex;
return oShortCodeModel;
}
}
//HtmlHelper Extension
public static MvcHtmlString RenderShortCode(this HtmlHelper htmlHelper, string IdOrExprssion)
{
#region Get short code data
var oShortCode = ShortCodeHelper.GetShortCode(IdOrExprssion);
#endregion
var oMvcHtmlString = new MvcHtmlString(IdOrExprssion);
var oRegexFilter = new RegexFilter();
var shortCodeModel = oRegexFilter.GetShortCodeValues(oShortCode.Expression);
var ostringBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(shortCodeModel.TableName))
{
ostringBuilder.AppendLine("SELECT ");
ostringBuilder.AppendLine((shortCodeModel.KeyValue.Count > 0 ? string.Join(",", shortCodeModel.KeyValue.Select(x => x.Value)) : "*"));
ostringBuilder.AppendLine(" FROM ");
ostringBuilder.AppendLine(oShortCode.TableName);
ostringBuilder.AppendLine(" WITH(NOLOCK) ");
if (oShortCode.FilterCode.Count() > 0)
{
ostringBuilder.AppendLine("WHERE ");
foreach (var filterCode in oShortCode.FilterCode)
{
ostringBuilder.AppendLine(filterCode.FilterColumnName);
ostringBuilder.AppendLine(filterCode.Operator);
ostringBuilder.AppendLine(filterCode.FilterColumnValue);
}
}
}
var oDyanamicData = DBHelper.GetDataTable(ostringBuilder.ToString(), System.Data.CommandType.Text, new List<SqlParameter>());
if (oDyanamicData != null)
{
if (oShortCode.IsHtmlRender)
{
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
string key = Convert.ToString(oDyanamicData.Columns[j]);
string value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
if (oShortCode.DisplayCode.Count > 0)
{
var displayCode = oShortCode.DisplayCode.FirstOrDefault(x => x.DisplayColumnName == key);
if (displayCode != null && !string.IsNullOrEmpty(displayCode?.ReplaceKey))
{
oShortCode.DefinedHtml = oShortCode.DefinedHtml.Replace(displayCode.ReplaceKey, value);
}
}
}
}
return new MvcHtmlString(oShortCode.DefinedHtml);
}
else
{
string key = string.Empty, value = string.Empty;
#region For Json
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
key = Convert.ToString(oDyanamicData.Columns[j]);
value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
return new MvcHtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(dataList));
#endregion
}
}
return oMvcHtmlString;
}
Can anyone help me solved above in SQL server or prepared query in store procedure

Convert EntityFramework to Raw SQL Queries in MVC

I am trying to make a crud calendar in my .net, my question is, How do make the below entity framework codes to SQL queries?
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Thanks guys
You can run raw query in entity framework with dc.Database.ExecuteSqlCommand() command like below:
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
dc.Database.ExecuteSqlCommand(&#"
UPDATE Events
SET Subject = {e.Subject},
Start = {e.Start},
End = {End},
Description = {Description},
IsFullDay = {IsFullDay},
ThemeColor = {ThemeColor},
WHERE EventID = {e.EventID}
IF ##ROWCOUNT = 0
INSERT INTO Events (EventID, Subject, Start, End, Description, IsFullDay, ThemeColor)
VALUES ({e.EventID}, {e.Subject}, ...)
");
status = true;
}
return new JsonResult { Data = new { status = status }
};

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

Current user belongs to a specific group in sharepoint?

I have created a code to find out the current logged in user belongs to a particular group or not but I am getting an error saying that
IsCurrentUserMemberOfGroup(gName1); contains some invalid arguments.
Please help ?
Here is my code
SPSite oSite = (SPSite)properties.OpenWeb().Site;
SPWeb oWeb = oSite.OpenWeb();
SPGroupCollection myGroup = oWeb.Groups;
foreach (SPGroup gName in myGroup)
{
//string gname1 = gName.ToString();
SPGroup gName1 = gName;
if (gName1.Name == "Final Approval Group")
{
//SPGroup lGroup = oWeb.Groups["Final Approval Group"];
bool answer = oWeb.IsCurrentUserMemberOfGroup(gName1);
fValue = 1;
break;
}
}
Try using gName1.ID since IsCurrentUserMemberOfGroup takes an int argument.
SPGroupCollection myGroup = oWeb.Groups;
foreach (SPGroup gName in myGroup) {
//string gname1 = gName.ToString();
SPGroup gName1 = gName;
if (gName1.Name == "Final Approval Group") {
//SPGroup lGroup = oWeb.Groups["Final Approval Group"];
bool answer = oWeb.IsCurrentUserMemberOfGroup(gName1.ID);
fValue = 1; break;
}
}

SharePoint get current list item from a collection

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"];
}