public static SPFieldLookupValueCollection GetLookFieldIDS(string lookupValues, SPList lookupSourceList) { SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection(); string[] lookups = lookupValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string lookupValue in lookups) { SPQuery query = new Microsoft.SharePoint.SPQuery(); query.Query = String.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", lookupValue); SPListItemCollection listItems = lookupSourceList.GetItems(query); foreach (Microsoft.SharePoint.SPListItem item in listItems) { SPFieldLookupValue value = new SPFieldLookupValue(item.ID.ToString()); lookupIds.Add(value); break; } } return lookupIds; }
public static ArrayList GetActiveCustomers(DateTime hitDate, SPWeb web) { ArrayList results = new ArrayList(); DateTime baseDate = new DateTime(hitDate.Year, hitDate.Month, 1); var targetList = web.Lists.TryGetList("Karty pracy"); if (targetList != null) { targetList.Items.Cast<SPListItem>() .Where(i => (DateTime)i["colData"] >= baseDate) .Where(i => (DateTime)i["colData"] <= hitDate) .Where(i => i["colCzyRozliczony"] == null || (bool)i["colCzyRozliczony"] != true) .GroupBy(i => i["selKlient"]) .ToList() .ForEach(item => { string groupItemKey = item.Key.ToString(); int customerId = new SPFieldLookupValue(groupItemKey).LookupId; results.Add(customerId); }); } return results; }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); try { string lopnummerStr = properties.Web.Properties["lopnummer"]; int lopnummer; if (int.TryParse(lopnummerStr, out lopnummer)) { string nyttLopnummer = (lopnummer + 1).ToString(); string code = properties.Web.Properties["municipalAreaCode"]; string letter = properties.Web.Properties["municipalRegionLetter"]; string kundnummer = letter + code + "-" + nyttLopnummer; string strAdress = (string)properties.ListItem[new Guid("b5c833ef-df4e-44f3-9ed5-316ed61a59c9")]; if (!string.IsNullOrEmpty(strAdress)) { SPFieldLookupValue adress = new SPFieldLookupValue(strAdress); properties.ListItem[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")] = adress.LookupValue; } else { properties.ListItem[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")] = kundnummer; } properties.ListItem[new Guid("353eabaa-f0d3-40cc-acc3-4c6b23d3a64f")] = kundnummer; properties.ListItem.Update(); properties.Web.Properties["lopnummer"] = nyttLopnummer; properties.Web.Properties.Update(); } WriteLog("Success", EventLogEntryType.Information, 1000); } catch (Exception ex) { WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2000); } }
public static SPFieldLookupValueCollection GetLookFieldIDS(ClientContext context, string lookupValues, List lookupSourceList) { SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection(); string[] lookups = lookupValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string lookupValue in lookups) { CamlQuery query = new CamlQuery(); query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", lookupValue); ListItemCollection listItems = lookupSourceList.GetItems(query); context.Load(lookupSourceList); context.Load(listItems); context.ExecuteQuery(); foreach (ListItem item in listItems) { SPFieldLookupValue value = new SPFieldLookupValue(Convert.ToInt32(item["ID"]), item["Title"].ToString()); lookupIds.Add(value); break; } } return(lookupIds); }
private void RenderDonorPanel(SPListItem item) { if (item["Donor"] != null) { var donor = new SPFieldLookupValue(item["Donor"].ToString()); try { var linkField = SPContext.Current.Web.Lists["Donors"].GetItemById(donor.LookupId); DonorLink.Text = donor.LookupValue; if (linkField["Website"] != null) { var link = new SPFieldUrlValue(linkField["Website"].ToString()); DonorLink.NavigateUrl = link.Url; DonorLink.Target = "_blank"; } DonorPanel.Visible = true; } catch (ArgumentException) { //throw new Exception(string.Format("The requested Donor \"{0}\" was not found for the item titled \"{1}\".", donor, item.Title)); DonorPanel.Visible = false; } } else { DonorPanel.Visible = false; } }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties); try { _dbg = "butik"; object oButik = properties.ListItem[new Guid("a209aa87-f7e4-46cf-8865-37ea0002294b")]; string strButik = oButik as string; if (strButik != null) { SPFieldLookupValue butik = new SPFieldLookupValue(strButik); _dbg = "ct"; string contenttype = properties.ListItem.ContentType.Name; _dbg = "id"; int id = properties.ListItemId; _dbg = "set"; properties.ListItem["Title"] = contenttype + " #" + id.ToString() + " - " + butik.LookupValue; _dbg = "klar"; properties.ListItem.Update(); _dbg = "upd"; WriteLog("ItemAdded", EventLogEntryType.Information, 1002); } } catch (Exception ex) { WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace + "\r\n\r\nDebug:\r\n" + _dbg, EventLogEntryType.Error, 2002); } }
protected override void OnInit(EventArgs e) { CustomDropDownList field = base.Field as CustomDropDownList; if (field.AllowMultipleValues) { if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.Display) { if (base.ListItemFieldValue != null) { _fieldVals = base.ListItemFieldValue as SPFieldLookupValueCollection; } else { _fieldVals = new SPFieldLookupValueCollection(); } } if (ControlMode == SPControlMode.New) { _fieldVals = new SPFieldLookupValueCollection(); } base.OnInit(e); Initialize_multi_value((CustomDropDownList)this.Field); } else { if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.Display) { if (base.ListItemFieldValue != null) { _fieldVal = base.ListItemFieldValue as SPFieldLookupValue; } else { _fieldVal = new SPFieldLookupValue(); } } if (ControlMode == SPControlMode.New) { _fieldVal = new SPFieldLookupValue(); } base.OnInit(e); Initialize((CustomDropDownList)base.Field); } }
public override string GetValidatedString(object value) { if (this.Required) { string _s = string.Format(CultureInfo.InvariantCulture, "{0} is required.", this.Title); if (value == null) { throw new SPFieldValidationException(_s); } else { if (this.AllowMultipleValues) { SPFieldLookupValueCollection c = value as SPFieldLookupValueCollection; if (c.Count < 0) { throw new SPFieldValidationException(_s); } } else { SPFieldLookupValue v = value as SPFieldLookupValue; if (v.LookupId < 1 && (string.IsNullOrEmpty(v.LookupValue) || v.LookupValue == "(None)")) { throw new SPFieldValidationException(_s); } } } } return(base.GetValidatedString(value)); }
internal Employee GetEmployeedetails(string name) { var empEntity = new Employee(); using (var site = new SPSite(SPContext.Current.Site.Url)) { using (var web = site.OpenWeb()) { SPUser user = web.CurrentUser; hdnCurrentUsername.Value = user.Name; SPListItemCollection currentUserDetails = GetListItemCollection(web.Lists[Utilities.EmployeeScreen], "Employee Name", name, "Status", "Active"); foreach (SPListItem currentUserDetail in currentUserDetails) { empEntity.EmpId = currentUserDetail[Utilities.EmployeeId].ToString(); empEntity.EmployeeType = currentUserDetail[Utilities.EmployeeType].ToString(); empEntity.Department = currentUserDetail[Utilities.Department].ToString(); empEntity.Desigination = currentUserDetail[Utilities.Designation].ToString(); empEntity.DOJ = DateTime.Parse(currentUserDetail[Utilities.DateofJoin].ToString()); empEntity.ManagerWithID = currentUserDetail[Utilities.Manager].ToString(); var spv = new SPFieldLookupValue(currentUserDetail[Utilities.Manager].ToString()); empEntity.Manager = spv.LookupValue; } } } return(empEntity); }
/// <summary> /// Responds to delegation updating. /// </summary> /// <param name="properties">The properties.</param> /// <param name="web">The web.</param> public static void RespondToDelegationUpdating(SPItemEventProperties properties, SPWeb web) { SPFieldLookupValue statusValue = new SPFieldLookupValue(properties.AfterProperties[DelegationsFields.DelegationStatus.Name].ToString()); string description = properties.AfterProperties[DelegationsFields.DelegationNote.Name].ToString(); var list = web.Lists[properties.ListId]; var listItem = list.Items.GetItemById(properties.ListItemId); if (statusValue.LookupId == Draft) { if (String.IsNullOrEmpty(description)) { properties.Cancel = true; properties.ErrorMessage = "Description cannot be empty."; properties.Status = SPEventReceiverStatus.CancelWithError; } else { SPFieldUserValue userValue = new SPFieldUserValue(properties.Web, properties.ListItem[SPBuiltInFieldId.Author].ToString()); Permissions.GrantPermission(web, listItem, userValue.User.Name, SPRoleType.Contributor); SendMail(web, userValue.User.Email, description); } } else if (statusValue.LookupId == ForApproval) { SPFieldUserValue userValue = new SPFieldUserValue(web, properties.ListItem[SPBuiltInFieldId.Author].ToString()); Permissions.RevokePremission(web, listItem, userValue.User.Name); SendMail(web, approvalEmail, properties.ListItem.Url); } else if (statusValue.LookupId == Approved) { SPFieldUserValue userValue = new SPFieldUserValue(properties.Web, properties.ListItem[SPBuiltInFieldId.Author].ToString()); Permissions.GrantPermission(web, listItem, userValue.User.Name, SPRoleType.Reader); SendMail(web, userValue.User.Email, properties.ListItem.Url); } }
public void MakeTimeregTest() { var employeeName = "Morten Madsen"; var customer = "NCMOD"; int toolkitCaseId = 14641; double hours = 0.5; DateTime doneDate = DateTime.Now; var list = "tidsregistrering"; var oList = _clientContext.Web.Lists.GetByTitle(list); _clientContext.Load(oList); _clientContext.ExecuteQuery(); var doneBy = new SPFieldLookupValue(419, employeeName); var author = new SPFieldLookupValue(419, employeeName); var toolkitCase = new SPFieldLookupValue(toolkitCaseId, $"{customer}-{toolkitCaseId}"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = oList.AddItem(itemCreateInfo); oListItem["Hours"] = hours; oListItem["DoneBy"] = doneBy; oListItem["Author"] = author; oListItem["Case"] = toolkitCase; oListItem["DoneDate"] = doneDate; oListItem.Update(); _clientContext.ExecuteQuery(); var id = Convert.ToInt32(oListItem.Id.ToString()); Assert.AreNotEqual(id, -1); }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object Convert(object value, DataRowConversionArguments arguments) { var lookupValue = value as SPFieldLookupValue; if (value == DBNull.Value) { return null; } if (lookupValue == null) { var stringValue = value as string; if (!string.IsNullOrEmpty(stringValue)) { lookupValue = new SPFieldLookupValue(stringValue); } } if (lookupValue != null) { var lookupField = new SPFieldLookup(arguments.FieldCollection, arguments.ValueKey); if (lookupField.LookupWebId == Guid.Empty || lookupField.LookupWebId == arguments.Web.ID) { return GetLookupFieldValue(arguments.Web, lookupField.LookupList, this._projectedFieldName, lookupValue.LookupId); } using (var web = arguments.Web.Site.OpenWeb(lookupField.LookupWebId)) { return GetLookupFieldValue(web, lookupField.LookupList, this._projectedFieldName, lookupValue.LookupId); } } return null; }
public override string GetValidatedString(object value) { if (this.Required) { string _s = string.Format(CultureInfo.InvariantCulture, "Você deve especificar um valor para este campo obrigatório.", this.Title); if (value == null) { throw new SPFieldValidationException(_s); } else { if (this.AllowMultipleValues) { SPFieldLookupValueCollection c = value as SPFieldLookupValueCollection; if (c.Count < 0) { throw new SPFieldValidationException(_s); } } else { SPFieldLookupValue v = value as SPFieldLookupValue; if (v.LookupId < 1 && (string.IsNullOrEmpty(v.LookupValue) || v.LookupValue == "(Nenhum)")) { throw new SPFieldValidationException(_s); } } } } return(base.GetValidatedString(value)); }
public static int GetLookupIdFromValue(this SPFieldLookup field, string fieldValue) { int ret = 0; try //assume fieldValue has both ID and Value { SPFieldLookupValue pairValue = new SPFieldLookupValue(fieldValue); if (pairValue != null && pairValue.LookupId != 0) { return(pairValue.LookupId); } } catch { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web = SPContext.Current.Site.OpenWeb(field.LookupWebId)) { SPList list = web.Lists.GetList(new Guid(field.LookupList), false); SPListItemCollection founds = list.FindItems(field.LookupField, fieldValue); if (founds.Count > 0) { ret = founds[0].ID; } } }); } return(ret); }
private static bool GetIsTaskAssignedToUserOrGroup(SPWorkflowTask task, int userId) { SPFieldLookupValue value2 = new SPFieldLookupValue(task[SPBuiltInFieldId.AssignedTo].ToString()); int lookupId = value2.LookupId; return((lookupId == userId) || SPContext.Current.Web.IsCurrentUserMemberOfGroup(lookupId)); }
private void button4_Click(object sender, EventArgs e) { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = oList.AddItem(itemCreateInfo); var box = comboBox1.SelectedItem; string boxx = box.ToString(); if (boxx == null) { this.label5.Text = "Add genre"; } var box2 = comboBox2lang.SelectedItem; var tex1 = textBox3title.Text; var tex2 = textBox5pages.Text; var tex4 = textBox4.Text; oListItem["Title"] = tex1; try { oListItem["Genre"] = new SPFieldLookupValue(boxx); } catch (ArgumentException) { } oListItem["Pages"] = tex2; oListItem["Author4"] = tex4; oListItem["Language"] = box2; oListItem.Update(); clientContext.ExecuteQuery(); }
internal Employee GetEmployeedetails(string name) { var empEntity = new Employee(); using (var site = new SPSite(SPContext.Current.Site.Url)) { using (var web = site.OpenWeb()) { SPUser user = web.CurrentUser; hdnCurrentUsername.Value = user.Name; SPListItemCollection currentUserDetails = GetListItemCollection(web.Lists[Utilities.EmployeeScreen], "Employee Name", name, "Status", "Active"); foreach (SPListItem currentUserDetail in currentUserDetails) { empEntity.EmpId = currentUserDetail[Utilities.EmployeeId].ToString(); empEntity.EmployeeType = currentUserDetail[Utilities.EmployeeType].ToString(); empEntity.Department = currentUserDetail[Utilities.Department].ToString(); empEntity.Desigination = currentUserDetail[Utilities.Designation].ToString(); empEntity.DOJ = DateTime.Parse(currentUserDetail[Utilities.DateofJoin].ToString()); empEntity.ManagerWithID = currentUserDetail[Utilities.Manager].ToString(); var spv = new SPFieldLookupValue(currentUserDetail[Utilities.Manager].ToString()); empEntity.Manager = spv.LookupValue; } } } return empEntity; }
private static void GetAssociatedListItems(SPItemEventProperties properties, Dictionary <string, object> data) { var dict = new Dictionary <Guid, int>(); SPFieldCollection fields = properties.List.Fields; foreach (SPField field in fields) { try { if (field.Hidden || field.Type != SPFieldType.Lookup) { continue; } object value = properties.ListItem[field.InternalName]; if (value == null) { continue; } var lookup = ((SPFieldLookup)field); if (lookup.AllowMultipleValues) { continue; } Guid listId; if (!Guid.TryParse(lookup.LookupList, out listId)) { continue; } var val = value as string; if (string.IsNullOrEmpty(val)) { continue; } var lookupValue = new SPFieldLookupValue(val); if (!dict.ContainsKey(listId)) { dict.Add(listId, lookupValue.LookupId); } else { dict[listId] = lookupValue.LookupId; } } catch { } } List <string> list = dict.Select(lv => string.Format(@"{0}|{1}", lv.Key, lv.Value)).ToList(); data.Add("AssociatedListItems", string.Join(",", list.Distinct().ToArray())); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { dateTimeDate.SelectedDate = DateTime.Now; using (var site = new SPSite(SPContext.Current.Site.Url)) { using (var web = site.OpenWeb()) { var currentYear = SPContext.Current.Web.Lists.TryGetList(Utilities.CurrentYear).GetItems(); foreach (SPListItem currentYearValue in currentYear) { hdnCurrentYear.Value = currentYearValue["Title"].ToString(); } string currentFnclYear = hdnCurrentYear.Value; string finalcialEndYear = currentFnclYear.Substring( currentFnclYear.IndexOf("-", System.StringComparison.Ordinal) + 1); string finalcialStartYear = currentFnclYear.Substring(0, 4); hdnFinancialStratmonth.Value = string.Empty; var financialStrartMonthllist = SPContext.Current.Web.Lists.TryGetList(Utilities.Financialstartmonth).GetItems(); foreach (SPListItem financialStrartmonth in financialStrartMonthllist) { hdnFinancialStratmonth.Value = financialStrartmonth["Title"].ToString(); } string tempfinStrtDate = hdnFinancialStratmonth.Value.Trim() + "/01/" + finalcialStartYear; string tempfinEndDate = (int.Parse(hdnFinancialStratmonth.Value) - 1).ToString() + "/01/" + finalcialEndYear; hdnFnclStarts.Value = GetFirstDayOfMonth(DateTime.Parse(tempfinStrtDate)).ToShortDateString(); hdnFnclEnds.Value = GetLastDayOfMonth(DateTime.Parse(tempfinEndDate)).ToShortDateString(); var list = SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeScreen); if (list != null) { ddlEmployee.Items.Clear(); ddlEmployee.Items.Add("--Select--"); var collection = GetListItemCollection(list, "Status", "Active"); //, "Employee Type", "Permanent"); foreach (SPListItem item in collection) { var spv = new SPFieldLookupValue(item["Employee Name"].ToString()); var listItem = new ListItem(spv.LookupValue, item["Employee Name"].ToString()); ddlEmployee.Items.Add(listItem); } } } } } }
/// <summary> /// aktualizuje pole _NazwaPrezentowana /// </summary> private static void Update_LookupRefFields(SPListItem item) { // aktualizacja odwołań do lookupów item["_TypZawartosci"] = item["ContentType"].ToString(); item["_Biuro"] = item["selBiuro"] != null ? new SPFieldLookupValue(item["selBiuro"].ToString()).LookupValue : string.Empty; item["_ZatrudniaPracownikow"] = item["colZatrudniaPracownikow"] != null && (bool)item["colZatrudniaPracownikow"] ? "TAK" : string.Empty; if (item["selDedykowanyOperator_Podatki"] != null) { item["_DedykowanyOperator_Podatki"] = new SPFieldLookupValue(item["selDedykowanyOperator_Podatki"].ToString()).LookupValue; } if (item["selDedykowanyOperator_Kadry"] != null) { item["_DedykowanyOperator_Kadry"] = new SPFieldLookupValue(item["selDedykowanyOperator_Kadry"].ToString()).LookupValue; } if (item["selDedykowanyOperator_Audyt"] != null) { item["_DedykowanyOperator_Audyt"] = new SPFieldLookupValue(item["selDedykowanyOperator_Audyt"].ToString()).LookupValue; } //nazwa prezentowana string np = string.Empty; switch (item.ContentType.Name) { case "KPiR": case "KSH": np = string.Format("{0} NIP:{1}", item["colNazwaSkrocona"]!=null?item["colNazwaSkrocona"].ToString(): item.Title, item["colNIP"] != null ? item["colNIP"].ToString() : string.Empty); break; case "Firma": string nazwa = item["colNazwa"]!=null?item["colNazwa"].ToString():string.Empty; string nip = item["colNIP"] != null ? item["colNIP"].ToString() : string.Empty; np = string.Format(@"::{0} NIP:{1}", nazwa, nip ); break; case "Firma zewnętrzna": string nazwaFirmyZewn = item["colNazwa"] != null ? item["colNazwa"].ToString() : string.Empty; np = "::" + nazwaFirmyZewn.Trim() + "::"; break; case "Osoba fizyczna": string npNazwsko = item["colNazwisko"] != null ? item["colNazwisko"].ToString().Trim() : string.Empty; string npImie = item["colImie"] != null ? item["colImie"].ToString().Trim() : string.Empty; string npPESEL = item["colPESEL"] != null ? item["colPESEL"].ToString().Trim() : string.Empty; np = string.Format(@":{0} {1} PESEL:{2}", npNazwsko, npImie, npPESEL); break; case "Klient": np = "?"+item["colNazwaSkrocona"].ToString(); break; case "Powiązanie": np = string.Format(@"{0}\{1}", BLL.Tools.Get_LookupValue(item, "selKlient_NazwaSkrocona"), BLL.Tools.Get_LookupValue(item, "selKlient")); break; default: break; } item["_NazwaPrezentowana"] = np; item.SystemUpdate(); }
private void MatchSPFieldTextOrChoice(SPListItem targetSPListItem, SPField targetSPField, SPWeb sourceSPWeb, SPField sourceSPField, string sourceValue) { // get just the term label if (sourceSPField is TaxonomyField) { targetSPListItem[targetSPField.Id] = this.SubstringBefore(sourceValue, TaxonomyField.TaxonomyGuidLabelDelimiter.ToString(CultureInfo.InvariantCulture)); } // for lookup and custom fields, convert RAW values into plain text else if (sourceSPField.Type == SPFieldType.Lookup || sourceSPField.Type == SPFieldType.Invalid) { SPFieldLookup spFieldLookupField = sourceSPField as SPFieldLookup; if (spFieldLookupField == null) { // TODO: multi-valued source fields should be deconstructed properly! targetSPListItem[targetSPField.Id] = this.SubstringAfter(sourceValue, ";#"); } else { if (spFieldLookupField.AllowMultipleValues) { string formatted = string.Empty; SPFieldLookupValueCollection spFieldLookupValues = new SPFieldLookupValueCollection(sourceValue); foreach (SPFieldLookupValue spFieldLookupValue in spFieldLookupValues) { formatted = formatted + ";" + spFieldLookupValue.LookupValue; } targetSPListItem[targetSPField.Id] = formatted.TrimStart(';'); } else { SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(sourceValue); targetSPListItem[targetSPField.Id] = spFieldLookupValue.LookupValue; } } } else if (sourceSPField.Type == SPFieldType.User) { // TODO: TEST THIS !!!!!!!! string formatted = string.Empty; SPFieldUserValueCollection spFieldUserValues = new SPFieldUserValueCollection(sourceSPWeb, sourceValue); foreach (SPFieldLookupValue spFieldLookupValue in spFieldUserValues) { formatted = formatted + ";" + spFieldLookupValue.LookupValue; } targetSPListItem[targetSPField.Id] = formatted.TrimStart(';'); } else { targetSPListItem[targetSPField.Id] = this.SubstringAfter(sourceValue, ";#"); } }
//TODO: Add support for multiple timeregs per day for a case (i.e. group them by case id) //Do some loop over list where we create Microsoft.SharePoint.Client.ListItem and put into SP.List oList -- SEE UNIT TEST PROJECT //Send to Toolkit -- SEE UNIT TEST PROJECT public virtual void MakeTimeregistrations(IEnumerable <Timeregistration> timeregs, ToolkitUser toolkitUser, Toolkit toolkit) { var clientContext = new ClientContext(toolkit.Url) { Credentials = new NetworkCredential(toolkitUser.Name, toolkitUser.SecurePassword, toolkitUser.Domain) }; const string timeregSpListName = "tidsregistrering"; var timeregSpList = clientContext.Web.Lists.GetByTitle(timeregSpListName); clientContext.Load(timeregSpList); clientContext.ExecuteQuery(); var listItems = new Dictionary <CaseDateTimeslot, ListItem>(); var doneBy = new SPFieldLookupValue(toolkit.UserId, toolkitUser.Name); var author = new SPFieldLookupValue(toolkit.UserId, toolkitUser.Name); var itemCreateInfo = new ListItemCreationInformation(); var timeregsByCaseIdDateTimeslot = GroupTimeregistrations(timeregs); foreach (var caseDateTimeslotGroup in timeregsByCaseIdDateTimeslot) { var sharepointListItem = timeregSpList.AddItem(itemCreateInfo); var caseDateTimeslot = caseDateTimeslotGroup.Key; var toolkitCase = new SPFieldLookupValue(caseDateTimeslot.CaseId, $"{toolkit.CustomerName}-{caseDateTimeslot.CaseId}"); var doneDate = caseDateTimeslot.Date; var hours = CalculateDuration(caseDateTimeslotGroup.Value); sharepointListItem["Hours"] = hours; sharepointListItem["DoneBy"] = doneBy; sharepointListItem["Author"] = author; sharepointListItem["Case"] = toolkitCase; sharepointListItem["DoneDate"] = doneDate; sharepointListItem.Update(); listItems.Add(caseDateTimeslot, sharepointListItem); } try { clientContext.ExecuteQuery(); } catch (Exception) { throw new Exception($"Unable to save timeregs to Toolkit. Toolkit: DisplayName={toolkit.DisplayName}, Url={toolkit.Url}"); } foreach (var item in listItems) { var isSynchronised = item.Value.Id != -1; foreach (var timereg in timeregsByCaseIdDateTimeslot[item.Key]) { timereg.IsSynchronized = isSynchronised; } } }
public static string GetStringValue(this SPListItem item, string fieldname) { if (item[fieldname] == null || string.IsNullOrEmpty(item[fieldname].ToString().Trim())) { return(string.Empty); } SPField field = item.Fields.GetField(fieldname); string ReturnValue; switch (field.Type) { case SPFieldType.Lookup: if (((SPFieldLookup)field).AllowMultipleValues == false) { SPFieldLookupValue lookup = new SPFieldLookupValue(item[fieldname].ToString()); ReturnValue = lookup.LookupValue; } else { SPFieldLookupValueCollection lookup = new SPFieldLookupValueCollection(item[fieldname].ToString()); ReturnValue = ""; foreach (SPFieldLookupValue v in lookup) { ReturnValue += v.LookupValue + ";"; } ReturnValue.TrimEnd(';'); } break; case SPFieldType.User: if (((SPFieldUser)field).AllowMultipleValues == false) { SPFieldUserValue users = new SPFieldUserValue(item.Web, item[fieldname].ToString()); ReturnValue = users.User.Name; } else { SPFieldUserValueCollection users = new SPFieldUserValueCollection(item.Web, item[fieldname].ToString()); ReturnValue = users[0].User.Name; } break; case SPFieldType.MultiChoice: SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue(item[fieldname].ToString()); ReturnValue = ""; for (int i = 0; i < values.Count; i++) { ReturnValue += values[i].ToString() + ";"; } ReturnValue.TrimEnd(';'); break; default: ReturnValue = item[fieldname].ToString().Trim(); break; } return(ReturnValue); }
/// <summary> /// For the specified object, attempt to create a SharePoint Field Values Hashtable based on the object's contents. /// </summary> /// <param name="properties"></param> /// <returns></returns> public static Hashtable GetFieldValuesHashtableFromPropertyObject(object properties) { Hashtable htProperties = null; if (properties != null && properties != Null.Value && properties is ObjectInstance) { var propertiesInstance = properties as ObjectInstance; htProperties = new Hashtable(); foreach (var property in propertiesInstance.Properties) { var propertyName = property.Name.ToString(CultureInfo.InvariantCulture); //TODO: Convert to appropriate FieldValues object propertyValue; if (property.Value is ObjectInstance && (property.Value as ObjectInstance).HasProperty("type")) { var fieldValue = (property.Value as ObjectInstance); var type = fieldValue.GetPropertyValue("type"); switch (type.ToString()) { case "Lookup": propertyValue = new SPFieldLookupValue(fieldValue.GetPropertyValue("fieldValue").ToString()); break; case "MultiChoice": propertyValue = new SPFieldMultiChoiceValue(fieldValue.GetPropertyValue("fieldValue").ToString()); break; case "MultiChoiceColumn": propertyValue = new SPFieldMultiColumnValue(fieldValue.GetPropertyValue("fieldValue").ToString()); break; case "Url": propertyValue = new SPFieldUrlValue(fieldValue.GetPropertyValue("fieldValue").ToString()); break; case "User": //TODO: Maybe get another web? propertyValue = new SPFieldUserValue(SPBaristaContext.Current.Web, fieldValue.GetPropertyValue("fieldValue").ToString()); break; default: propertyValue = fieldValue.ToString(); break; } } else { propertyValue = property.Value.ToString(); } htProperties.Add(propertyName, propertyValue); } } return(htProperties); }
/// <summary> /// ToSPFieldLookupValue /// </summary> /// <param name="lookupItem"></param> /// <returns></returns> public static SPFieldLookupValue ToSPFieldLookupValue(this LookupItem lookupItem) { SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue() { LookupId = lookupItem.LookupId }; return(fieldLookupValue); }
/// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) { //test {0} and test {1} //base.ItemAdded(properties); string webUrl = properties.WebUrl; SPUserToken sysAdminToken = properties.Site.SystemAccount.UserToken; using (SPSite site = new SPSite(webUrl, sysAdminToken)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.GetList("/Lists/eventListTest"); SPQuery query = new SPQuery() { Query = string.Format(@"<Where><Eq><FieldRef Name='ListId' /><Value Type='Text'>{0}</Value></Eq></Where>", properties.ListId.ToString().ToUpper()) }; SPListItemCollection items = list.GetItems(query); foreach (SPListItem item in items) { if (item["Params"].ToString().Length > 0) { string[] pNames = item["Params"].ToString().Split(','); object[] param = new object[pNames.Length]; for (int i = 0; i < pNames.Length; i++) { if (pNames[i].ToUpper().Contains(".LOOKUPID")) { string[] s = pNames[i].Split('.'); param[i] = new SPFieldLookupValue(properties.ListItem[s[0]].ToString()).LookupId; } else if (pNames[i].ToUpper().Contains(".LOOKUPVALUE")) { string[] s = pNames[i].Split('.'); param[i] = new SPFieldLookupValue(properties.ListItem[s[0]].ToString()).LookupValue; } else { param[i] = properties.ListItem[pNames[i]].ToString(); } } properties.ListItem[item["Field"].ToString()] = string.Format(item["Value"].ToString(), param); } else { properties.ListItem[item["Field"].ToString()] = string.Format(item["Value"].ToString()); } } if (items.Count > 0) { properties.ListItem.SystemUpdate(false); } } } }
private ShimSPListItem GetListItem() { return(new ShimSPListItem() { IDGet = () => Id, ItemGetGuid = _ => DummyString, ItemGetString = _ => DummyString, ItemSetStringObject = (_, val) => { _item = val as SPFieldLookupValue; } }); }
private void AddDropdown(SPFieldLookup field) { DropList = new DropDownList(); DropList.ID = "Lookup"; DropList.TabIndex = TabIndex; DropList.DataSource = DataSource; DropList.DataValueField = "ValueField"; DropList.DataTextField = "TextField"; DropList.ToolTip = SPHttpUtility.NoEncode(field.Title); DropList.DataBind(); object fieldValue = null; SPFieldLookupValue lookupVal = null; try { fieldValue = ListItem[LookupField.InternalName]; if (fieldValue != null) { lookupVal = new SPFieldLookupValue(fieldValue.ToString()); } } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } if (lookupVal != null) { LookupValue = lookupVal.ToString(); if (base.Field.Required) { DropList.SelectedIndex = lookupVal.LookupId - 1 >= 0 ? lookupVal.LookupId - 1 : 0; } else { DropList.SelectedIndex = lookupVal.LookupId; } HasValueSet = true; } DropList.Attributes.Add( "onchange", "window.ModifiedDropDown.UpdateChildrenValues('" + field.InternalName + "');"); if (LookupData.Parent != "" && lookupVal == null) { DropList.Enabled = false; } Controls.Add(DropList); }
private void LoadDepartments() { try { this.ddlDepartment.DataValueField = "ID"; if (this.IsVietnameseLanguage) { this.ddlDepartment.DataTextField = "VietnameseName"; } else { this.ddlDepartment.DataTextField = "Name"; } var departments = new List <Department>(); if (this.CurrentItem[EmployeeRequirementSheetsList.Fields.RecruitmentDepartment] != null) { SPFieldLookupValue departmentLookupValue = ObjectHelper.GetSPFieldLookupValue(this.CurrentItem[EmployeeRequirementSheetsList.Fields.RecruitmentDepartment]); var department = this.ApprovalBaseManagerObject.DepartmentDAL.GetByID(departmentLookupValue.LookupId); if (department != null) { departments.Add(department); } } else { // Người của phòng ban nào thì làm đơn cho phòng ban của mình thôi. Không làm đơn giúp cho phòng ban khác. var currentEmployee = this.ApprovalBaseManagerObject.CurrentEmployee; if (currentEmployee != null) { if (currentEmployee.Department != null) { var department = this.ApprovalBaseManagerObject.DepartmentDAL.GetByID(currentEmployee.Department.LookupId); if (department != null) { departments.Add(department); } } } } this.ddlDepartment.DataSource = departments; this.ddlDepartment.DataBind(); #region MOD. 2017.09.29. // Tiến 29.09.2017: Chỗ bộ phận anh Disable luôn dùm em. TFS #1587. //this.ddlDepartment.Enabled = this.isEditable; this.ddlDepartment.Enabled = false; #endregion } catch (Exception ex) { ULSLogging.LogError(ex); ULSLogging.LogMessageToFile($"-- Error occurs on RecruitmentFormUserControl: {ex.Message}"); } }
public virtual int MakeTimeregistration(Timeregistration timereg, ToolkitUser toolkitUser, Toolkit toolkit) { var clientContext = new ClientContext(toolkit.Url) { Credentials = new NetworkCredential(toolkitUser.Name, toolkitUser.SecurePassword, toolkitUser.Domain) }; const string timeregList = "tidsregistrering"; var sharepointList = clientContext.Web.Lists.GetByTitle(timeregList); clientContext.Load(sharepointList); clientContext.ExecuteQuery(); var itemCreateInfo = new ListItemCreationInformation(); var sharepointListItem = sharepointList.AddItem(itemCreateInfo); var success = timereg.CouldConvertDurationToHours(); if (!success) { return(-1); } var doneBy = new SPFieldLookupValue(toolkit.UserId, toolkitUser.Name); var author = new SPFieldLookupValue(toolkit.UserId, toolkitUser.Name); if (timereg.IsWorkPackage) { sharepointListItem["Case"] = FindRelatedCaseForWorkPackage(clientContext, timereg.CaseId); var toolkitWorkPackage = new SPFieldLookupValue(timereg.CaseId, ""); sharepointListItem["WorkPackage"] = toolkitWorkPackage; } else { var toolkitCase = new SPFieldLookupValue(timereg.CaseId, $"{toolkit.CustomerName}-{timereg.CaseId}"); sharepointListItem["Case"] = toolkitCase; } //sharepointListItem["Hours"] = timereg.Hours; sharepointListItem["Hours"] = timereg.Hours; sharepointListItem["DoneBy"] = doneBy; sharepointListItem["Author"] = author; sharepointListItem["DoneDate"] = timereg.DoneDate; try { sharepointListItem.Update(); clientContext.ExecuteQuery(); return(sharepointListItem.Id); } catch { return(-1); } }
static void Main(string[] args) { string personListName = "Person"; string[] jobs = { "Developer", "Admin", "Organization" }; string[] skills = { "C#", "TypeScript", "React" }; SPSite col = new SPSite("http://SP2016"); SPWeb web = col.RootWeb; SPList list = web.Lists.TryGetList(personListName); if (list == null) { var skillslist = addListWithItems(web, "Skills", "A skills List", skills); var joblist = addListWithItems(web, "Jobs", "A job List", jobs); Guid id = web.Lists.Add(personListName, "A Person List", SPListTemplateType.GenericList); list = web.Lists.TryGetList(personListName); var jobCol = list.Fields.AddLookup("Jobs", joblist.ID, true); SPFieldLookup jobLookup = (SPFieldLookup)list.Fields[jobCol]; jobLookup.LookupField = joblist.Fields["Title"].InternalName; jobLookup.Title = "Job"; jobLookup.Update(); list.Update(); var skillCol = list.Fields.AddLookup("Skills", skillslist.ID, true); SPFieldLookup skillLookup = (SPFieldLookup)list.Fields[skillCol]; skillLookup.LookupField = skillslist.Fields["Title"].InternalName; skillLookup.Title = "Skills"; skillLookup.AllowMultipleValues = true; skillLookup.Update(); list.Update(); var person = list.Items.Add(); person["Title"] = "Bob der Baumeister"; person["Job"] = new SPFieldLookupValue(1, jobs[0]); var sks = new SPFieldLookupValueCollection { new SPFieldLookupValue(1, skills[0]), new SPFieldLookupValue(3, skills[2]) }; person["Skills"] = sks; person.Update(); } foreach (SPListItem item in list.Items) { SPFieldLookupValue job = new SPFieldLookupValue(item["Job"].ToString()); string skillsString = GetSkills(item); Console.WriteLine("{0} works as a {1} with skills {2}", item["Title"], job.LookupValue, skillsString); } }
protected override void OnInit(EventArgs e) { if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.Display) { if (base.ListItemFieldValue != null) { _fieldVal = base.ListItemFieldValue as SPFieldLookupValue; } else { _fieldVal = new SPFieldLookupValue(); } } if (ControlMode == SPControlMode.New) { _fieldVal = new SPFieldLookupValue(); } base.OnInit(e); Initialize(); }
public static LookupItem ToLookupItem(this SPFieldLookupValue fieldLookupValue) { LookupItem lookupItem = null; if (fieldLookupValue != null) { lookupItem = new LookupItem { LookupId = fieldLookupValue.LookupId, LookupValue = fieldLookupValue.LookupValue }; } return lookupItem; }
public Dictionary <string, string> GetFieldsAndValues(SPItemEventDataCollection data, IEnumerable <string> compositeKeyFields) { Dictionary <string, string> fieldsAndValues = new Dictionary <string, string>(); foreach (string compositeKeyField in compositeKeyFields) { SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(data[compositeKeyField].ToString()); fieldsAndValues.Add(compositeKeyField, fieldLookupValue.LookupId.ToString()); } return(fieldsAndValues); }
private static void SetFieldLookup(SPListItem listItem, PropertyInfo prop, T valor, string nameInternal) { var collectionLookup = new SPFieldLookupValue(listItem[nameInternal].ToString()); var lookup = new LookupFieldEnc { Key = collectionLookup.LookupId.ToString(), Value = collectionLookup.LookupValue }; prop.SetValue(valor, lookup); }
public static string GetLookupFileContent(this SPListItem item, string fieldName) { var lookupValue = new SPFieldLookupValue(item[fieldName].ToString()); var listId = new Guid(((SPFieldLookup)item.Fields.GetFieldByInternalName(fieldName)).LookupList); var list = item.Web.Lists[listId]; var litem = list.GetItemById(lookupValue.LookupId); using (var reader = new StreamReader(litem.File.OpenBinaryStream())) { return(reader.ReadToEnd()); } }
public void ShouldItAlsoUpdateTheLookupValue() { using (var site = new SPSite("http://winsrv2008")) using (var web = site.OpenWeb()) { var list = web.Lists["Assets"]; var item = list.GetItemById(262); item["Room"] = new SPFieldLookupValue(19, null); item.Update(); } }
/// <summary> /// 已更新项. /// </summary> public void ItemUpdatedbak(SPItemEventProperties properties) { string nameField = properties.List.Fields.GetField("完成百分比").InternalName; string fType = properties.List.Fields.GetField("活动类型").InternalName; string fDiDian = properties.List.Fields.GetField("活动地点").InternalName; string fObject = properties.List.Fields.GetField("活动对象").InternalName; string fStart = properties.List.Fields.GetField("开始日期").InternalName; string fEnd = properties.List.Fields.GetField("截止日期").InternalName; string fAssigned = properties.List.Fields.GetField("截止日期").InternalName; if (properties.ListItem["ParentID"] != null) {// sub level if (properties.ListItem[nameField].ToString() == "1") { string taskName = properties.ListItem["Title"].ToString(); string typeName = properties.ListItem[fType].ToString(); string diDianName = properties.ListItem[fDiDian].ToString(); string objName = properties.ListItem[fObject].ToString(); DateTime start = DateTime.Parse(properties.ListItem[fStart].ToString()); DateTime end = DateTime.Parse(properties.ListItem[fEnd].ToString()); SPUser[] assignedTo = (SPUser[])properties.ListItem[fAssigned]; SPFieldLookupValue taskID = new SPFieldLookupValue(properties.ListItem.ID, taskName); } } string fDoc = properties.List.Fields.GetField("文档对象").InternalName;//查阅项 SPField f1 = properties.List.Fields.GetFieldByInternalName(fDoc); SPFieldLookup field = f1 as SPFieldLookup; string lookList = field.LookupList; SPListItem item = properties.ListItem; SPFieldLookupValue fValue = new SPFieldLookupValue(item[fDoc].ToString()); string[] choices = Regex.Split(fValue.ToString(), ";#"); string docUrl = GetDocUrl(properties.WebUrl, field.LookupWebId, field.LookupList, fValue.LookupId.ToString()); this.EventFiringEnabled = false; item["Title"] = properties.Web.Url;// +docUrl;// fValue.LookupId + "\\" + item[fDoc] + fValue.LookupValue; item.Update(); this.EventFiringEnabled = true; //using (SPWeb targetSite = new SPSite(properties.WebUrl).AllWebs[field.LookupWebId]) //{ // // Get the name of the list where this field gets information. // SPList targetList = targetSite.Lists[new Guid(field.LookupList)]; // // Get the name of the field where this field gets information. // SPField targetField = targetList.Fields.GetFieldByInternalName(field.LookupField); // //this.EventFiringEnabled = false; // //item["Title"] = targetList.Title + "\\" + item[fDoc] + targetField.Title; // //item.Update(); // //this.EventFiringEnabled = true; //} }
const string targetList = @"Faktury elektroniczne - import"; //"intFakturyElektroniczne"; public static void Execute(SPListItem item, SPWeb web) { int okresId = new SPFieldLookupValue(item["selOkres"].ToString()).LookupId; SPList list = web.Lists.TryGetList(targetList); list.Items.Cast<SPListItem>() .ToList() .ForEach(oItem => { Import_Faktura(oItem, okresId); }); }
const string targetList = @"Faktury za obsługę - import"; //"intFakturyZaObsluge"; #endregion Fields #region Methods internal static void Execute(Microsoft.SharePoint.SPItemEventProperties properties, Microsoft.SharePoint.SPWeb web) { SPListItem sItem = properties.ListItem; int okresId = new SPFieldLookupValue(sItem["selOkres"].ToString()).LookupId; SPList list = web.Lists.TryGetList(targetList); list.Items.Cast<SPListItem>() .ToList() .ForEach(item => { Import_DaneOFakturze(web, item, okresId); }); }
/// <summary> /// This method adds tasks ref to the list in the root site. /// </summary> /// <param name="Task">SPListItem</param> public int AddTask(string Title, DateTime DueDate, string Approver, string DocumentAuthor, string TaskUrl, SPWeb Web, SPFieldLookupValue PublicationLocation) { SPList ObjTaskList = Web.Lists["Document Approval Tasks"]; SPListItem _newTask = ObjTaskList.Items.Add(); _newTask["Title"] = Title; _newTask["Document Approver"] = Web.SiteGroups[Approver]; //SPHelper.SetFieldValueUser(_newTask, "Document Approver",Approver); SPHelper.SetFieldValueUser(_newTask, "Document Author",DocumentAuthor); _newTask["Due Date"] = DueDate; _newTask["Task Ref"] = TaskUrl; _newTask["Published Location"] = PublicationLocation; _newTask.SystemUpdate(); Web.Update(); return _newTask.ID; }
public object FromSpValue(object value) { if (value == null||string.IsNullOrEmpty(Field.LookupList)) return null; if (!Field.AllowMultipleValues) { var fieldValue = new SPFieldLookupValue(value.ToString()); return new ObjectReference(new Guid(Field.LookupList), fieldValue.LookupId, fieldValue.LookupValue); } var fieldValues = new SPFieldLookupValueCollection(value.ToString()); return fieldValues.Select(fieldValue => new ObjectReference(new Guid(Field.LookupList), fieldValue.LookupId, fieldValue.LookupValue)).ToList(); }
const string targetList = @"Faktury elektroniczne - import"; //"intFakturyElektroniczne"; #endregion Fields #region Methods internal static void Execute(SPItemEventProperties properties, SPWeb web) { int okresId = new SPFieldLookupValue(properties.ListItem["selOkres"].ToString()).LookupId; SPList list = web.Lists.TryGetList(targetList); //if (list != null) //{ list.Items.Cast<SPListItem>() .ToList() .ForEach(item => { Import_Faktura(item, okresId); }); //} }
public void PendingLeaves() { try { using (var site = new SPSite(SPContext.Current.Site.Url)) { using (var web = site.OpenWeb()) { var managerList = web.Lists.TryGetList(Utilities.ReportingTo); var leavelist = web.Lists.TryGetList(Utilities.LeaveRequest); var pendings = GetListItemCollection(leavelist, "Status", "Pending", "Year", hdnCurrentYear.Value); if (pendings.Count > 0) { DataTable table = PendingstableStructure(); if (leavelist != null) { var managerListDetails = managerList.GetItems(); foreach (SPListItem managerListDetail in managerListDetails) { DataRow dataRow = table.NewRow(); var spv = new SPFieldLookupValue(managerListDetail["Reporting Managers"].ToString()); dataRow["Manager"] = spv.LookupValue; var pendingDetails = GetListItemCollection(leavelist, "Status", "Pending", "Year", hdnCurrentYear.Value, "RequestedTo", spv.LookupValue); dataRow["No Of Leave Pending"] = pendingDetails.Count; table.Rows.Add(dataRow); } btnUpdate.Enabled = false; } ViewState["PendingResult"] = table; } } } } catch (Exception ex) { lblErr.Text = ex.Message; } }
private void AddPurchase() { SPFieldLookupValueCollection RequestDetails = new SPFieldLookupValueCollection(); var RequestDetailList = Utility.GetListFromURL(Constants.REQUEST_DETAIL_LIST_URL, SPContext.Current.Web); foreach (RepeaterItem RequestDetail in repeaterRequestDetail.Items) { TextBox txtProductName = RequestDetail.FindControl("txtProductName") as TextBox; TextBox txtQuantity = RequestDetail.FindControl("txtQuantity") as TextBox; TextBox txtPrice = RequestDetail.FindControl("txtPrice") as TextBox; TextBox txtDescription = RequestDetail.FindControl("txtDescription") as TextBox; if (!string.IsNullOrEmpty(txtProductName.Text)) { SPListItem RequestDetailItem = RequestDetailList.AddItem(); RequestDetailItem[SPBuiltInFieldId.Title] = txtProductName.Text; RequestDetailItem["Quantity"] = txtQuantity.Text.Replace(",", string.Empty); RequestDetailItem["Price"] = txtPrice.Text.Replace(",", string.Empty); RequestDetailItem["Description"] = txtDescription.Text; RequestDetailItem.Update(); SPFieldLookupValue spFieldLookupValue = new SPFieldLookupValue(RequestDetailItem.ID, RequestDetailItem.Title); RequestDetails.Add(spFieldLookupValue); } } var purchaseList = Utility.GetListFromURL(Constants.REQUEST_LIST_URL, SPContext.Current.Web); SPListItem purchaseItem = SPContext.Current.ListItem; purchaseItem[SPBuiltInFieldId.Title] = ffTitle.Value;//Constants.PURCHASE_TITLE_PREFIX + literalUserRequestValue.Text; purchaseItem["DateRequest"] = DateTime.Now; purchaseItem["UserRequest"] = SPContext.Current.Web.CurrentUser; purchaseItem["DepartmentRequest"] = literalDepartmentRequestValue.Text; purchaseItem["TypeOfApproval"] = hiddenTypeOfApproval.Value; purchaseItem["RequestDetail"] = RequestDetails; purchaseItem["References"] = ffReferences.Value; //PurchaseHelper.GetMultipleItemSelectionValues(purchaseReferences); if(peChief.IsValid && peChief.ResolvedEntities.Count > 0) purchaseItem["Chief"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peChief.ResolvedEntities[0]).Key); //ffChief.Value; // if (peBuyer.IsValid && peBuyer.ResolvedEntities.Count > 0) purchaseItem["Buyer"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peBuyer.ResolvedEntities[0]).Key); //ffBuyer.Value; // if (peApprover.IsValid && peApprover.ResolvedEntities.Count > 0) purchaseItem["Approver"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peApprover.ResolvedEntities[0]).Key); //ffApprover.Value; // if (peAccountant.IsValid && peAccountant.ResolvedEntities.Count > 0) purchaseItem["Accountant"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peAccountant.ResolvedEntities[0]).Key); //ffAccountant.Value; // if (peConfirmer.IsValid && peConfirmer.ResolvedEntities.Count > 0) purchaseItem["Confirmer"] = SPContext.Current.Web.EnsureUser(((PickerEntity)peConfirmer.ResolvedEntities[0]).Key); //ffConfirmer.Value; // SaveButton.SaveItem(SPContext.Current, false, ""); }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public object Convert(object value, ConversionArguments arguments) { var lookupValue = value as SPFieldLookupValue; if (value == DBNull.Value) { return null; } if (lookupValue == null) { var stringValue = value as string; if (!string.IsNullOrEmpty(stringValue)) { lookupValue = new SPFieldLookupValue(stringValue); } } return lookupValue != null ? new LookupValue(lookupValue) : null; }
public override void SetUp() { base.TestFixtureSetUp(); roomList = web.Lists["Rooms"]; var roomItem1 = roomList.Items.Add(); roomItem1["Room Number"] = "Room 1"; roomItem1.Update(); roomId1 = roomItem1.ID; var roomItem2 = roomList.Items.Add(); roomItem2["Room Number"] = "Room 2"; roomItem2.Update(); roomId2 = roomItem2.ID; assetList = web.Lists["Assets"]; assetItem = assetList.Items.Add(); assetItem["Room"] = new SPFieldLookupValue(roomId1, null); assetItem.Update(); lookupField = new LookupFieldValue(new SPListItemWrapper(assetItem), "Room"); }
/// <summary> /// Converts the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="arguments">The arguments.</param> /// <returns> /// The converted value. /// </returns> public override object Convert(object value, SharePointListItemConversionArguments arguments) { var lookupValue = value as SPFieldLookupValue; if (lookupValue == null) { var stringValue = value as string; if (!string.IsNullOrEmpty(stringValue)) { lookupValue = new SPFieldLookupValue(stringValue); } } if (lookupValue != null) { var lookupField = arguments.ListItem.Fields.GetFieldByInternalName(arguments.ValueKey) as SPFieldLookup; if (lookupField != null) { if (lookupField.LookupWebId == Guid.Empty || lookupField.LookupWebId == arguments.ListItem.Web.ID) { return GetLookupFieldValue(arguments.ListItem.Web, lookupField.LookupList, this._projectedFieldName, lookupValue.LookupId); } else { using (var web = arguments.ListItem.Web.Site.OpenWeb(lookupField.LookupWebId)) { return GetLookupFieldValue(web, lookupField.LookupList, this._projectedFieldName, lookupValue.LookupId); } } } else { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "No lookup field with Internal Name '{0}' could be found.", arguments.ValueKey)); } } return null; }
public static string Define_KEY(SPListItem item) { string ct = item["ContentType"].ToString(); if (ct == "Zadanie" || ct == "Element" || ct == "Folder") { return String.Empty; } int klientId = 0; int okresId = 0; if (item["selKlient"] != null) { klientId = new SPFieldLookupValue(item["selKlient"].ToString()).LookupId; } if (item["selOkres"] != null) { okresId = new SPFieldLookupValue(item["selOkres"].ToString()).LookupId; } return Define_KEY(ct, klientId, okresId); }
public static SPFieldLookupValue GetMenuType(string listName, int docID, string colName) { SPFieldLookupValue result = null; SPSecurity.RunWithElevatedPrivileges(() => { using (var site = new SPSite(SPContext.Current.Web.Site.ID)) { using (var web = site.OpenWeb(SPContext.Current.Web.ID)) { try { string listUrl = web.Url + "/Lists/" + listName; var mtItem = web.GetList(listUrl).GetItemById(docID); result = new SPFieldLookupValue(Convert.ToString(mtItem[colName])); } catch (Exception ex) { Utilities.LogToUls(ex); } } } }); return result; }
/// <summary> /// Get and return table with correct url /// </summary> /// <param name="categoryListName">categoryListName</param> /// <param name="items"></param> /// <returns></returns> public static DataTable GetTableWithCorrectUrl(string categoryListName, SPListItemCollection items) { var dataTable = items.GetDataTable(); if (!dataTable.Columns.Contains(FieldsName.CategoryId)) { dataTable.Columns.Add(FieldsName.CategoryId, Type.GetType("System.String")); } if (!dataTable.Columns.Contains(FieldsName.ArticleStartDateTemp)) { dataTable.Columns.Add(FieldsName.ArticleStartDateTemp, Type.GetType("System.String")); } if (items != null && items.Count > 0) { string imagepath = string.Empty; ImageFieldValue imageIcon; SPFieldUrlValue advLink; DateTime time = new DateTime(); for (int i = 0; i < items.Count; i++) { imagepath = Convert.ToString(items[i][FieldsName.NewsRecord.English.ThumbnailImage]); imageIcon = items[i][FieldsName.NewsRecord.English.PublishingPageImage] as ImageFieldValue; if (imageIcon != null) { dataTable.Rows[i][FieldsName.NewsRecord.English.ThumbnailImage] = GetThumbnailImagePath(imageIcon.ImageUrl); } else { if (imagepath.Length > 2) dataTable.Rows[i][FieldsName.NewsRecord.English.ThumbnailImage] = imagepath.Trim().Substring(0, imagepath.Length - 2); else { dataTable.Rows[i][FieldsName.NewsRecord.English.ThumbnailImage] = imagepath; } } if (items[i].Fields.ContainsField(FieldsName.NewsRecord.English.LinkAdv)) { advLink = new SPFieldUrlValue(Convert.ToString(items[i][FieldsName.NewsRecord.English.LinkAdv])); dataTable.Rows[i][FieldsName.NewsRecord.English.LinkAdv] = advLink.Url; } if (!string.IsNullOrEmpty(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName]))) { SPFieldLookupValue catLK = new SPFieldLookupValue(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName])); dataTable.Rows[i][FieldsName.CategoryId] = catLK.LookupId; } time = Convert.ToDateTime(dataTable.Rows[i][FieldsName.ArticleStartDates]); dataTable.Rows[i][FieldsName.ArticleStartDateTemp] = string.Format("Ngày {0}/{1}/{2}", time.Day, time.Month, time.Year); } } return dataTable; }
public static DataTable GetTableWithCorrectUrlHotNews(string categoryListName, DataTable dataTable) { var items = dataTable.Copy(); if (!dataTable.Columns.Contains(FieldsName.CategoryId)) { dataTable.Columns.Add(FieldsName.CategoryId, Type.GetType("System.String")); } if (!dataTable.Columns.Contains(Constants.ListCategoryName)) { dataTable.Columns.Add(Constants.ListCategoryName, Type.GetType("System.String")); } if (!dataTable.Columns.Contains(Constants.ListName)) { dataTable.Columns.Add(Constants.ListName, Type.GetType("System.String")); } if (items != null && items.Rows.Count > 0) { string imagepath = string.Empty; ImageFieldValue imageIcon; SPFieldUrlValue advLink; for (int i = 0; i < items.Rows.Count; i++) { if (items.Columns.Contains(FieldsName.NewsRecord.English.LinkAdv)) { advLink = new SPFieldUrlValue(Convert.ToString(items.Rows[i][FieldsName.NewsRecord.English.LinkAdv])); dataTable.Rows[i][FieldsName.NewsRecord.English.LinkAdv] = advLink.Url; } dataTable.Rows[i][FieldsName.NewsRecord.English.ShortContent] = StripHtml(Convert.ToString(dataTable.Rows[i][FieldsName.NewsRecord.English.ShortContent])); //if (!string.IsNullOrEmpty(Convert.ToString(items.Rows[i][FieldsName.NewsRecord.English.CategoryName]))) //{ // SPFieldLookupValue catLK = new SPFieldLookupValue(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName])); // dataTable.Rows[i][FieldsName.CategoryId] = catLK.LookupId; //} var list = SPContext.Current.Web.Lists.GetList(new Guid(Convert.ToString(dataTable.Rows[i]["ListId"])), true); var listUrl = list.RootFolder.ServerRelativeUrl.Split('/'); dataTable.Rows[i][Constants.ListName] = listUrl[listUrl.Length - 1]; SPFieldLookup catFile = (SPFieldLookup)list.Fields.GetFieldByInternalName(FieldsName.NewsRecord.English.CategoryName); listUrl = SPContext.Current.Web.Lists.GetList(new Guid(catFile.LookupList), true).RootFolder.ServerRelativeUrl.Split('/'); dataTable.Rows[i][Constants.ListCategoryName] = listUrl[listUrl.Length - 1]; var listItem = list.GetItemById(Convert.ToInt32(dataTable.Rows[i]["ID"])); imagepath = Convert.ToString(items.Rows[i][FieldsName.NewsRecord.English.ThumbnailImage]); imageIcon = listItem[FieldsName.NewsRecord.English.PublishingPageImage] as ImageFieldValue; if (imageIcon != null) { dataTable.Rows[i][FieldsName.NewsRecord.English.ThumbnailImage] = imageIcon.ImageUrl; } else { if (imagepath.Length > 2) dataTable.Rows[i][FieldsName.NewsRecord.English.ThumbnailImage] = imagepath.Trim().Substring(0, imagepath.Length - 2); else { dataTable.Rows[i][FieldsName.NewsRecord.English.ThumbnailImage] = imagepath; } } if (!string.IsNullOrEmpty(Convert.ToString(listItem[FieldsName.NewsRecord.English.CategoryName]))) { SPFieldLookupValue catLK = new SPFieldLookupValue(Convert.ToString(listItem[FieldsName.NewsRecord.English.CategoryName])); dataTable.Rows[i][FieldsName.CategoryId] = catLK.LookupId; } } } return dataTable; }
public static DataTable SearchNews(string keyWord) { string camlQuery = string.Empty; if (!string.IsNullOrEmpty(keyWord)) { keyWord = HttpContext.Current.Server.UrlDecode(keyWord); keyWord = SPEncode.HtmlEncode(keyWord); //camlQuery = //string.Format( // "<Where><Or><Contains><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Contains><Or><Contains><FieldRef Name='{2}' /><Value Type='Note'>{1}</Value></Contains><Contains><FieldRef Name='{3}' /><Value Type='Note'>{1}</Value></Contains></Or></Or></Where>", // "Title", keyWord, FieldsName.NewsRecord.English.ShortContent, FieldsName.NewsRecord.English.PublishingPageContent); camlQuery = string.Format(@"<Where> <And> <Neq> <FieldRef Name='Status' /> <Value Type='Boolean'>1</Value> </Neq> <And> <Lt> <FieldRef Name='{0}' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>{1}</Value> </Lt> <And> <Eq> <FieldRef Name='{2}' /> <Value Type='Number'>{3}</Value> </Eq> <Or> <Contains> <FieldRef Name='Title' /> <Value Type='Text'>{4}</Value> </Contains> <Or> <Contains> <FieldRef Name='ShortContent' /> <Value Type='Note'>{4}</Value> </Contains> <Contains> <FieldRef Name='PublishingPageContent' /> <Value Type='HTML'>{4}</Value> </Contains> </Or> </Or> </And> </And> </And> </Where>", FieldsName.ArticleStartDates, SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now), FieldsName.ModerationStatus, ModerationStatusValue, keyWord); } var query = new SPQuery(); query.Query = camlQuery; query.RowLimit = 100; DataTable table = null; SPSecurity.RunWithElevatedPrivileges(() => { using (var site = new SPSite(SPContext.Current.Web.Site.ID)) { using (var web = site.OpenWeb(SPContext.Current.Web.ID)) { try { string listUrl = web.Url + "/Lists/" + ListsName.English.NewsRecord; var list = web.GetList(listUrl); if (list != null) { var items = list.GetItems(query); if (items != null && items.Count > 0) { table = items.GetDataTable(); if (!table.Columns.Contains(FieldsName.CategoryId)) { table.Columns.Add(FieldsName.CategoryId, Type.GetType("System.String")); } if (!table.Columns.Contains(FieldsName.ArticleStartDateTemp)) { table.Columns.Add(FieldsName.ArticleStartDateTemp, Type.GetType("System.String")); } if (!table.Columns.Contains("ListCategoryName")) { table.Columns.Add("ListCategoryName", Type.GetType("System.String")); } if (!table.Columns.Contains("ListNewsName")) { table.Columns.Add("ListNewsName", Type.GetType("System.String")); } for (int i = 0; i < items.Count; i++) { table.Rows[i]["ListCategoryName"] = ListsName.English.NewsCategory; table.Rows[i]["ListNewsName"] = ListsName.English.NewsRecord; if (!string.IsNullOrEmpty(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName]))) { SPFieldLookupValue catLK = new SPFieldLookupValue(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName])); table.Rows[i][FieldsName.CategoryId] = catLK.LookupId; } var time = Convert.ToDateTime(items[i][FieldsName.ArticleStartDates]); table.Rows[i][FieldsName.ArticleStartDateTemp] = string.Format(" {0}/{1}/{2}", time.Day, time.Month, time.Year); } } } listUrl = web.Url + "/Lists/" + ListsName.English.CompanyRecord; var listCom = web.GetList(listUrl); if (listCom != null) { var items = listCom.GetItems(query); if (items != null && items.Count > 0) { if (table == null) { table = items.GetDataTable(); if (!table.Columns.Contains(FieldsName.CategoryId)) { table.Columns.Add(FieldsName.CategoryId, Type.GetType("System.String")); } if (!table.Columns.Contains(FieldsName.ArticleStartDateTemp)) { table.Columns.Add(FieldsName.ArticleStartDateTemp, Type.GetType("System.String")); } if (!table.Columns.Contains("ListCategoryName")) { table.Columns.Add("ListCategoryName", Type.GetType("System.String")); } if (!table.Columns.Contains("ListNewsName")) { table.Columns.Add("ListNewsName", Type.GetType("System.String")); } for (int i = 0; i < items.Count; i++) { table.Rows[i]["ListCategoryName"] = ListsName.English.CompanyCategory; table.Rows[i]["ListNewsName"] = ListsName.English.CompanyRecord; if (!string.IsNullOrEmpty(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName]))) { SPFieldLookupValue catLK = new SPFieldLookupValue(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName])); table.Rows[i][FieldsName.CategoryId] = catLK.LookupId; } var time = Convert.ToDateTime(items[i][FieldsName.ArticleStartDates]); table.Rows[i][FieldsName.ArticleStartDateTemp] = string.Format(" {0}/{1}/{2}", time.Day, time.Month, time.Year); } } else { var comItems = items.GetDataTable(); if (!comItems.Columns.Contains(FieldsName.CategoryId)) { comItems.Columns.Add(FieldsName.CategoryId, Type.GetType("System.String")); } if (!comItems.Columns.Contains(FieldsName.ArticleStartDateTemp)) { comItems.Columns.Add(FieldsName.ArticleStartDateTemp, Type.GetType("System.String")); } if (!comItems.Columns.Contains("ListCategoryName")) { comItems.Columns.Add("ListCategoryName", Type.GetType("System.String")); } if (!comItems.Columns.Contains("ListNewsName")) { comItems.Columns.Add("ListNewsName", Type.GetType("System.String")); } for (int i = 0; i < items.Count; i++) { comItems.Rows[i]["ListCategoryName"] = ListsName.English.CompanyCategory; comItems.Rows[i]["ListNewsName"] = ListsName.English.CompanyRecord; if (!string.IsNullOrEmpty(Convert.ToString(items[i][FieldsName.CompanyRecord.English.CategoryName]))) { SPFieldLookupValue catLK = new SPFieldLookupValue(Convert.ToString(items[i][FieldsName.CompanyRecord.English.CategoryName])); comItems.Rows[i][FieldsName.CategoryId] = catLK.LookupId; } var time = Convert.ToDateTime(items[i][FieldsName.ArticleStartDates]); comItems.Rows[i][FieldsName.ArticleStartDateTemp] = string.Format(" {0}/{1}/{2}", time.Day, time.Month, time.Year); table.ImportRow(comItems.Rows[i]); } } } } } catch (Exception ex) { Utilities.LogToUls(ex); } } } }); return table; }
/// <summary> /// This method handle create task event /// </summary> /// <param name="sender">object</param> /// <param name="e">EventArgs</param> private void logTaskCreated(object sender, EventArgs e) { //Add Task Refs in the root site. using (DocumentApprovalTasks tasks = new DocumentApprovalTasks()) { using (SPWeb ObjRootWeb = SPHelper.GetRootWeb(SPHelper.GetRootUrl(workflowProperties.SiteUrl))) { //Getting Created By - Login Name SPFieldUserValue val = new SPFieldUserValue(workflowProperties.Item.Web, workflowProperties.Item["Created By"] as string); SPUser usr = val.User; string _documentAuthor = usr.LoginName; string initiationData = workflowProperties.InitiationData; // Getting Publishbale Location ID var Publish_Location_ID = from _value in XElement.Load(new StringReader(EscapeXml(initiationData))).Elements("Publish_Location_ID") select _value; string _locationID = string.Empty; foreach (var ID in Publish_Location_ID) { _locationID = ID.Value; } // Getting Publishbale Location Name var Publish_Location_Name = from _value in XElement.Load(new StringReader(EscapeXml(initiationData))).Elements("Publish_Location_Name") select _value; string _locationName = string.Empty; foreach (var Name in Publish_Location_Name) { _locationName = Name.Value; } SPFieldLookupValue _publishableLocation = new SPFieldLookupValue(Convert.ToInt32(_locationID), _locationName); ; //_publishableLocation=new SPFieldLookupValue(location //Getting Approver - Login Name string _taskUrl = workflowProperties.Item.Web.Url + "/Lists/DocumentApprovalTasks/DispForm.aspx?ID=" + CreateAppovalTask.ListItemId.ToString(); //Add Task Ref in the root site _documentApprovalTaskId = tasks.AddTask(CreateAppovalTask.TaskProperties.Title, CreateAppovalTask.TaskProperties.DueDate, CreateAppovalTask.TaskProperties.AssignedTo, _documentAuthor, _taskUrl, ObjRootWeb, _publishableLocation); //int _groupID = Convert.ToInt32(CreateAppovalTask.TaskProperties.AssignedTo.ToString().Split(';')[0]); SPGroup _approverGroup = ObjRootWeb.Groups[CreateAppovalTask.TaskProperties.AssignedTo]; //Send Email notification to the approver SendApproverEmail(_approverGroup, "CLIF"); } } LogToHistoryListActivity log = (LogToHistoryListActivity)sender; if (log != null) { log.HistoryDescription = "Document approval task created."; } }
protected void Page_Load(object sender, EventArgs e) { DtDoj.MaxDate = DateTime.Now; // DtDOB.MaxDate = DateTime.Now; DtDOP.MaxDate = DateTime.Now; try { if (!Page.IsPostBack) { txtempid.Focus(); //divdop.Visible = false; try { var deplist = SPContext.Current.Web.Lists.TryGetList(Utilities.Department); if (deplist != null) { DdlDep.Items.Clear(); DdlDep.Items.Add("--Select--"); var collection = deplist.GetItems(); foreach (SPListItem item in collection) { DdlDep.Items.Add(item["Department"].ToString()); } } var desiglist = SPContext.Current.Web.Lists.TryGetList(Utilities.Designation); if (desiglist != null) { DdlDesignation.Items.Clear(); DdlDesignation.Items.Add("--Select--"); var collection = desiglist.GetItems(); foreach (SPListItem item in collection) { DdlDesignation.Items.Add(item["Designation"].ToString()); } } var leavetypelist = SPContext.Current.Web.Lists.TryGetList(Utilities.EmployeeType); if (leavetypelist != null) { DdlEmptype.Items.Clear(); DdlEmptype.Items.Add("--Select--"); var collection = leavetypelist.GetItems(); foreach (SPListItem item in collection) { DdlEmptype.Items.Add(item["Title"].ToString()); } } var managerlist = SPContext.Current.Web.Lists.TryGetList(Utilities.ReportingTo); if (managerlist != null) { ddlReportingTo.Items.Clear(); ddlReportingTo.Items.Add("--Select--"); var collection = managerlist.GetItems(); foreach (SPListItem item in collection) { var spv = new SPFieldLookupValue(item["Reporting Managers"].ToString()); var listItem = new ListItem(spv.LookupValue, item["Reporting Managers"].ToString()); ddlReportingTo.Items.Add(listItem); } } var currentYear = SPContext.Current.Web.Lists.TryGetList(Utilities.CurrentYear).GetItems(); foreach (SPListItem currentYearValue in currentYear) { hdnCurrentYear.Value = currentYearValue["Title"].ToString(); } var financialStartMont = SPContext.Current.Web.Lists.TryGetList(Utilities.Financialstartmonth).GetItems(); foreach (SPListItem finStrtmonth in financialStartMont) { hdnStrtFnclMnth.Value = finStrtmonth["Title"].ToString(); } } catch (Exception ex) { LblError.Text = ex.Message; } } } catch (Exception) { } //empGridView.DataSource = LoadEmpDetails(); //empGridView.DataBind(); }
protected void BtnRegisterClick(object sender, EventArgs e) { string dOP = ((TextBox)(DtDOP.Controls[0])).Text; string dOJ = ((TextBox)(DtDoj.Controls[0])).Text; // string dOB = ((TextBox)(DtDOB.Controls[0])).Text; if (SPContext.Current != null) { if (txtfristname.Text == "") { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; return; } if (txtlastname.Text == "") { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; return; } if (txtempid.Text == "") { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; return; } if (DdlDep.SelectedIndex < 1) { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; return; } if (DdlDesignation.SelectedIndex < 1) { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; return; } if (DdlEmptype.SelectedIndex < 1) { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; return; } //if (!ValidateDate(dOB, "MM/dd/yyyy")) //{ // LblError.Text = "Date format should be in 'MM/DD/YYYY' format."; // LblError.Text += "<br/>"; // DtDOB.ClearSelection(); // DtDOB.Focus(); // return; //} //else if (DateTime.Parse(dOB) > DateTime.Now) //{ // LblError.Text = "DOB should be Less than or equal to today."; // LblError.Text += "<br/>"; // divdop.Visible = true; // DtDOB.ClearSelection(); // DtDOB.Focus(); // return; //} if (string.IsNullOrEmpty(dOJ)) { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; // divdop.Visible = true; return; } if (!ValidateDate(dOJ, "MM/dd/yyyy")) { LblError.Text = "Date format should be in 'MM/DD/YYYY' format."; LblError.Text += "<br/>"; DtDoj.ClearSelection(); DtDoj.Focus(); return; } else if (DateTime.Parse(dOJ) > DateTime.Now) { LblError.Text = "DOJ should be Less than or equal to today."; LblError.Text += "<br/>"; // divdop.Visible = true; DtDoj.ClearSelection(); DtDoj.Focus(); return; } if (DdlEmptype.SelectedItem.Value.Trim() == "Permanent") { if (string.IsNullOrEmpty(dOP)) { LblError.Text = "All Fields are required field."; LblError.Text += "<br/>"; divdop.Visible = true; return; } else if (!ValidateDate(dOP, "MM/dd/yyyy")) { LblError.Text = "Date format should be in 'MM/DD/YYYY' format."; LblError.Text += "<br/>"; divdop.Visible = true; DtDOP.ClearSelection(); DtDOP.Focus(); return; } else if (DateTime.Parse(dOP) > DateTime.Now) { LblError.Text = "DOP should be Less than or equal to today."; LblError.Text += "<br/>"; divdop.Visible = true; DtDOP.ClearSelection(); DtDOP.Focus(); return; } else if (DateTime.Parse(dOP) < DateTime.Parse(dOJ)) { LblError.Text = "DOP should be greater than or equal to DOJ."; LblError.Text += "<br/>"; return; } } //if (DateTime.Parse(dOJ) < DateTime.Parse(dOB)) //{ // LblError.Text = "DOJ should be greater than DOB."; // LblError.Text += "<br/>"; // return; //} //else //{ try { using (var site = new SPSite(SPContext.Current.Site.Url)) { using (var web = site.OpenWeb()) { var list = web.Lists.TryGetList(Utilities.EmployeeScreen); web.AllowUnsafeUpdates = true; var newItem = list.Items.Add(); var empdupID = txtempid.Text; var query = new SPQuery { Query = @"<Where> <Eq> <FieldRef Name='Title' /> <Value Type='Text'>" + empdupID + @"</Value> </Eq> </Where>" }; var collection = list.GetItems(query); if (collection.Count == 0) { newItem[Utilities.EmployeeId] = txtempid.Text; newItem[Utilities.EmployeeName] = web.AllUsers[peoplepickeremp.Accounts[0].ToString()]; newItem[Utilities.FirstName] = txtfristname.Text; newItem[Utilities.LastName] = txtlastname.Text; newItem["Employee Type"] = DdlEmptype.SelectedValue; newItem["Department"] = DdlDep.SelectedValue; newItem["Designation"] = DdlDesignation.SelectedValue; //newItem[Utilities.Email] = Txtmail.Text; //newItem[Utilities.Mobile] = TxtContact.Text; newItem[Utilities.DateofJoin] = DateTime.Parse(GetFormatedDate(dOJ));// DtDoj.SelectedDate; //newItem[Utilities.DOB] = DateTime.Parse(GetFormatedDate(dOB)); //DtDOB.SelectedDate; if (DdlEmptype.SelectedItem.Text.Trim() == "Permanent") { newItem["Date of Permanent"] = DateTime.Parse(GetFormatedDate(dOP));//DtDOP.SelectedDate; } var entity = new PickerEntity { DisplayText = new SPFieldUserValue(web, ddlReportingTo.SelectedItem.Value) . User. LoginName }; newItem[Utilities.Manager] = web.AllUsers[entity.DisplayText]; newItem.Update(); var leavelist = web.Lists.TryGetList(Utilities.LeaveDays); var field = leavelist.Fields["Employee Type"]; var leaveDaysQuery = new SPQuery { Query = @"<Where> <Eq> <FieldRef Name='" + field.InternalName + @"' /> <Value Type='Lookup'>" + DdlEmptype.SelectedItem.Text + @"</Value> </Eq> </Where>" }; var leaveDayscollection = leavelist.GetItems(leaveDaysQuery); foreach (SPListItem leaveType in leaveDayscollection) { var empLeavelist = web.Lists.TryGetList(Utilities.EmployeeLeaves); var empLeaveItem = empLeavelist.Items.Add(); var emptype = new SPFieldLookupValue(leaveType["Employee Type"].ToString()); var lveType = new SPFieldLookupValue(leaveType["Leave Type"].ToString()); empLeaveItem["Employee ID"] = txtempid.Text; empLeaveItem[Utilities.EmployeeName] = web.AllUsers[peoplepickeremp.Accounts[0].ToString()]; empLeaveItem["Leave Type"] = leaveType["Leave Type"].ToString(); if (lveType.LookupValue == "Comp off") { empLeaveItem["Leave Balance"] = 0; } else if (lveType.LookupValue == "LOP") { empLeaveItem["Leave Balance"] = 0; } else if (lveType.LookupValue == "Optional") { empLeaveItem["Leave Balance"] = decimal.Parse(leaveType["Leave Days"].ToString()); } else { if (emptype.LookupValue.Trim() == "Permanent") { int dopMonth = DateTime.Parse(GetFormatedDate(dOP)).Month;// DtDOP.SelectedDate.Month; int monthDiff = GetMonthDifference(dopMonth); decimal leaves = decimal.Parse(leaveType["Leave Days"].ToString()) * monthDiff; if (leaves % 1 == 0) { int noOfleaves = Convert.ToInt16(leaves); empLeaveItem["Leave Balance"] = noOfleaves; } else { empLeaveItem["Leave Balance"] = leaves; } } else { decimal leaves = decimal.Parse(leaveType["Leave Days"].ToString()); if (leaves % 1 == 0) { int noOfleaves = Convert.ToInt16(leaves); empLeaveItem["Leave Balance"] = noOfleaves; } else { empLeaveItem["Leave Balance"] = leaves; } } } empLeaveItem["Leave utilized"] = 0; empLeaveItem["Leave Requested"] = 0; empLeaveItem["Reporting Manager"] = web.AllUsers[entity.DisplayText]; empLeaveItem[Utilities.Year] = hdnCurrentYear.Value; empLeaveItem["Employee Type"] = DdlEmptype.SelectedValue; empLeaveItem.Update(); } Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup(); SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, '1');</script>"); //Context.Response.Write("<script type='text/javascript'>window.Location = window.Location;</script>"); Context.Response.Flush(); Context.Response.End(); //Response.Redirect(SPContext.Current.Web.Url); web.AllowUnsafeUpdates = false; } else { LblError.Text = "Employee id is already exists."; LblError.Text += "<br/>"; } } } } catch (Exception ex) { LblError.Text = ex.Message; } // } } }
public static DataTable GetNewsByCatID(string listName, string catID, uint limitItems, bool isLatestNews) { string camlQuery = string.Format(@"<Where> <And> <Eq> <FieldRef Name='{0}' LookupId='TRUE' /> <Value Type='LookupMulti'>{1}</Value> </Eq> <And> <Neq> <FieldRef Name='Status' /> <Value Type='Boolean'>1</Value> </Neq> <And> <Leq> <FieldRef Name='{2}' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>{3}</Value> </Leq> <And> <Eq> <FieldRef Name='{4}' /> <Value Type='Number'>{5}</Value> </Eq> <Eq> <FieldRef Name='LatestNewsOnHomePage' /> <Value Type='Boolean'>TRUE</Value> </Eq> </And> </And> </And> </And> </Where><OrderBy> <FieldRef Name='{6}' Ascending='False' /> </OrderBy>", FieldsName.NewsRecord.English.CategoryName, catID, FieldsName.ArticleStartDates, SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now), FieldsName.ModerationStatus, ModerationStatusValue, FieldsName.ArticleStartDates); if (ListsName.English.CompanyRecord.Equals(listName)) { camlQuery = string.Format(@"<Where> <And> <Eq> <FieldRef Name='{0}' LookupId='TRUE' /> <Value Type='Lookup'>{1}</Value> </Eq> <And> <Neq> <FieldRef Name='Status' /> <Value Type='Boolean'>1</Value> </Neq> <And> <Leq> <FieldRef Name='{2}' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>{3}</Value> </Leq> <And> <Eq> <FieldRef Name='{4}' /> <Value Type='Number'>{5}</Value> </Eq> <Geq> <FieldRef Name='_EndDate' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>{3}</Value> </Geq> </And> </And> </And> </And> </Where> <OrderBy> <FieldRef Name='{6}' Ascending='False' /> </OrderBy>", FieldsName.NewsRecord.English.CategoryName, catID, FieldsName.ArticleStartDates, SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now), FieldsName.ModerationStatus, ModerationStatusValue, FieldsName.ModerationStatus); } if (ListsName.English.NewsCategory.Equals(listName)) { camlQuery = string.Format(@"<Where> <And> <Eq> <FieldRef Name='{0}' LookupId='TRUE' /> <Value Type='Lookup'>{1}</Value> </Eq> <Neq> <FieldRef Name='Status' /> <Value Type='Boolean'>1</Value> </Neq> </And> </Where> <OrderBy> <FieldRef Name='ID' Ascending='False' /> </OrderBy>", FieldsName.NewsCategory.English.ParentName, catID); } if (ListsName.English.SubNewsCategory.Equals(listName)) { camlQuery = string.Format(@"<Where> <And> <Eq> <FieldRef Name='{0}' LookupId='TRUE' /> <Value Type='Lookup'>{1}</Value> </Eq> <Neq> <FieldRef Name='Status' /> <Value Type='Boolean'>1</Value> </Neq> </And> </Where><OrderBy> <FieldRef Name='ID' Ascending='False' /> </OrderBy>", FieldsName.NewsCategory.English.ParentName, catID); } var query = new SPQuery(); query.Query = camlQuery; query.RowLimit = limitItems; DataTable table = null; SPSecurity.RunWithElevatedPrivileges(() => { using (var site = new SPSite(SPContext.Current.Web.Site.ID)) { using (var web = site.OpenWeb(SPContext.Current.Web.ID)) { try { string listUrl = web.Url + "/Lists/" + listName; var list = web.GetList(listUrl); if (list != null) { var items = list.GetItems(query); if (items != null && items.Count > 0) { table = items.GetDataTable(); if (!table.Columns.Contains(FieldsName.CategoryId)) { table.Columns.Add(FieldsName.CategoryId, Type.GetType("System.String")); } if (!table.Columns.Contains(FieldsName.ArticleStartDateTemp)) { table.Columns.Add(FieldsName.ArticleStartDateTemp, Type.GetType("System.String")); } for (int i = 0; i < items.Count; i++) { if (!string.IsNullOrEmpty(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName]))) { SPFieldLookupValue catLK = new SPFieldLookupValue(Convert.ToString(items[i][FieldsName.NewsRecord.English.CategoryName])); table.Rows[i][FieldsName.CategoryId] = catLK.LookupId; } var time = Convert.ToDateTime(items[i][FieldsName.ArticleStartDates]); table.Rows[i][FieldsName.ArticleStartDateTemp] = string.Format(" {0}/{1}/{2}", time.Day, time.Month, time.Year); } } } } catch (Exception ex) { Utilities.LogToUls(ex); } } } }); return table; }
/// <summary> /// Returns the value of a Lookup Field. /// </summary> public string GetFieldValueLookup(SPListItem item, string fieldName) { if (item != null) { SPFieldLookupValue lookupValue = new SPFieldLookupValue(item[fieldName] as string); return lookupValue.LookupValue; } else { return string.Empty; } }