Beispiel #1
0
        public SPListItemInstance Add()
        {
            var result = m_listItemCollection.Add();

            if (result == null)
            {
                return(null);
            }

            return(new SPListItemInstance(Engine, result));
        }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmitRequest_Click(object sender, EventArgs e)
        {
            //btnSubmit.Enabled = false;
            try
            {
                SPWeb mySite = SPContext.Current.Web;
                SPListItemCollection listItems = mySite.Lists["KMTDivisionalSites"].Items;
                SPListItem           item      = listItems.Add();

                item["SiteName"]         = txtSiteName.Text;
                item["SiteDescription"]  = txtSiteDescription.Text;
                item["SiteURL"]          = hdnSiteRoot.Value + txtLawsonDivisionNo.Text.ToString();
                item["LawsonDivisionNo"] = txtLawsonDivisionNo.Text.ToString();
                item["ZipCode"]          = txtZipCode.Text.ToString();
                item["PrimaryOwner"]     = txtPrimaryOwner.Text.ToString();
                item["SecondayOwner"]    = txtSecondayOwner.Text.ToString();
                item["Approver"]         = GetListValue("KMTConfig", "Key", "Approver", "Value", false);

                item.Update();
            }
            catch (Exception ex)
            {
                lblError.Text = "Error : " + ex.Message.ToString() + "  Trace : " + ex.Source.ToString();
                //LogException(ex);
            }
        }
Beispiel #3
0
        public static void WriteToList(string listName, string creativeName, string tel, string email)
        {
            SPUser lgUser  = SPContext.Current.Web.CurrentUser;
            string account = Common.GetAccount(lgUser.LoginName);

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite mySite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb spWeb = mySite.AllWebs[SPContext.Current.Web.ID])
                    {
                        SPList listNews = spWeb.Lists.TryGetList(listName);
                        if (listNews != null)
                        {
                            SPListItemCollection itemsNews = listNews.Items;

                            SPListItem item = itemsNews.Add();//将新建的博文添加到新闻列表
                            item["创意名称"]    = creativeName;
                            item["申报人"]     = lgUser.Name;
                            item["工号/学号"]   = account;

                            item["联系电话"] = tel;
                            item["电子邮箱"] = email;

                            item.Update();
                        }
                    }
                }
            });
        }
Beispiel #4
0
        public SPListItem AdicionaItemLista(string NomeLista, Dictionary <string, object> Valores)
        {
            Object objSaida = new object();


            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                SPWeb objSite = (new SPSite(SPContext.Current.Site.ID).AllWebs[SPContext.Current.Web.ID]);

                SPListItemCollection objLista = objSite.Lists[NomeLista].Items;

                //monta o Item da lista
                SPListItem objItem = objLista.Add();

                //para item no dicionario
                foreach (var i in Valores)
                {
                    objItem[i.Key] = i.Value;
                }

                objItem.Web.AllowUnsafeUpdates = true;

                objItem.Update();

                objSaida = objItem;
            });


            return(objSaida as SPListItem);
        }
Beispiel #5
0
        /// <summary>
        /// 已添加项.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            string newsID = "";

            if (properties.List.Fields.ContainsField("新闻ID"))
            {
                SPList listPost = properties.List;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite mySite = new SPSite(properties.Site.ID))
                    {
                        using (SPWeb spWeb = mySite.RootWeb)
                        {
                            SPList listNews = spWeb.Lists.TryGetList("新闻");
                            if (listNews != null)
                            {
                                SPListItemCollection itemsNews = listNews.Items;

                                SPListItem itemNews = itemsNews.Add();          //将新建的博文添加到新闻列表
                                UpdateNews(ref itemNews, properties);
                                newsID = itemNews.ID.ToString();
                            }
                        }
                    }
                });
            }
            if (newsID != "")
            {
                properties.ListItem["新闻ID"] = newsID; //新闻添加时返回新建新闻的ID
                properties.ListItem.Update();         //将新闻ID信息更新到对应博客项中
            }
        }
        public void crearUsuariosEnDirectorioDesdeAD(SPListItemCollection listaDirectorio, List <Usuario> listaAD)
        {
            foreach (Usuario user in listaAD)
            {
                if (user.email.ToString() != "" && (user.homePhone.ToString() != "" || user.mobile.ToString() != "" || user.pager.ToString() != "" || user.facsimileTelephoneNumber.ToString() != ""))
                {
                    SPListItem item = listaDirectorio.Add();

                    item["ows_Title"] = user.displayName.ToString();
                    if (user.facsimileTelephoneNumber != "" && user.telephoneNumber != "")
                    {
                        item["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString() + " / " + user.telephoneNumber.ToString(); // Fijo
                    }
                    else if (user.facsimileTelephoneNumber != "" && user.telephoneNumber == "")
                    {
                        item["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString(); // Fijo
                    }
                    else if (user.facsimileTelephoneNumber == "" && user.telephoneNumber != "")
                    {
                        item["ows_WorkPhone"] = user.telephoneNumber.ToString(); // Fijo
                    }
                    item["ows_CellPhone"]   = user.homePhone.ToString();
                    item["ows_HomePhone"]   = user.mobile.ToString();
                    item["ows_Email"]       = user.email.ToString();
                    item["ows_PagerNumber"] = user.pager.ToString();
                    item.Update();
                }
            }
        }
        // add New Item to List
        protected void addItem(object sender, EventArgs e)

        {
            string name        = productName.Value;
            string category    = productCategory.Value;
            string description = productDescription.Value;
            string year        = productYear.Value;
            string price       = productPrice.Value;

            SPList list = SPContext.Current.Web.Lists.TryGetList("Movies");
            SPListItemCollection listItems = list.Items;

            // Create new item in the list
            SPListItem item = listItems.Add();

            item["Movie_Name"]     = name;
            item["Movie_Category"] = category;
            item["Movie_Year"]     = Convert.ToInt32(year);
            item["Movie_Price"]    = Convert.ToInt32(price);

            item.Update();

            // Clear input boxes
            productName.Value        = "";
            productCategory.Value    = "";
            productDescription.Value = "";
            productYear.Value        = "";
            productPrice.Value       = "";

            this.BindRepeater();

            //  MessageBox.Show("Success", "Add new  item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        internal static void SetContactInfo(string name, string email, string phone, string message)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite sps = new SPSite(SPContext.Current.Web.Url))
                    using (SPWeb spw = sps.OpenWeb())
                    {
                        SPListItemCollection contactList = spw.Lists[LIST_MAIN_CONTACTS].Items;
                        SPListItem newItem = contactList.Add();

                        newItem["Title"] = name;
                        newItem["Correo_x0020_contacto"]         = email;
                        newItem["Tel_x00e9_fono_x0020_contacto"] = phone;
                        newItem["Mensaje_x0020_contacto"]        = message;

                        try
                        {
                            newItem.Web.AllowUnsafeUpdates = true;
                            newItem.Update();
                        }
                        finally
                        {
                            newItem.Web.AllowUnsafeUpdates = false;
                        }
                    }
            });
        }
        /// <summary>
        /// add new items to sharepoint lists (don't forget to declare the constructor)
        /// </summary>
        /// <param name="fields"> hash table that contains the item values (key: the column name Value: the value inside the column)</param>
        public void AddItemToList(Hashtable fields)
        {
            if (!IsHashtableValid(fields))
            {
                return;
            }
            try
            {
                SPListItemCollection itemCollection = GetItemCollection();
                if (itemCollection == null)
                {
                    return;
                }

                SPListItem  item = itemCollection.Add();
                ICollection keys = fields.Keys;
                FieldObject field;
                foreach (object key in keys)
                {
                    field = (FieldObject)fields[key];

                    switch (field.ValueType)
                    {
                    case FieldObject.Types.Text:
                        item[key.ToString()] = Convert.ToString(field.Value);
                        item.UpdateOverwriteVersion();
                        break;

                    case FieldObject.Types.Integer:
                        item[key.ToString()] = Convert.ToInt32(field.Value);
                        item.UpdateOverwriteVersion();
                        break;

                    case FieldObject.Types.DateTime:
                        item[key.ToString()] = Convert.ToDateTime(field.Value);
                        item.UpdateOverwriteVersion();
                        break;

                    case FieldObject.Types.Number:
                        item[key.ToString()] = Convert.ToDecimal(field.Value);
                        item.UpdateOverwriteVersion();
                        break;

                    case FieldObject.Types.Boolean:
                        item[key.ToString()] = Convert.ToBoolean(field.Value);
                        item.UpdateOverwriteVersion();
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                var log = new AppEventLog(AppException.ExceptionMessage(ex, "AddItemToList", "ClsHelper"));
                log.WriteToLog();
            }
        }
Beispiel #10
0
        private bool SaveRequest(int hiringId, int supplierId)
        {
            bool requestResult = true;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite sps = new SPSite(SPContext.Current.Web.Url))
                    using (SPWeb spw = sps.OpenWeb())
                    {
                        #region Validate previous entry
                        SPListItemCollection itemsList = spw.Lists[LIST_APPLICANTS].Items;

                        foreach (SPListItem item in itemsList)
                        {
                            int itemHiringId   = Convert.ToInt32(item["Convocatoria"].ToString().Remove(item["Convocatoria"].ToString().IndexOf(";#")));
                            int itemSupplierId = Convert.ToInt32(item["Proveedor"].ToString().Remove(item["Proveedor"].ToString().IndexOf(";#")));

                            if (itemHiringId == hiringId && itemSupplierId == supplierId)
                            {
                                requestResult = false;
                                break;
                            }
                        }
                        #endregion

                        #region Save the request
                        if (requestResult == true)
                        {
                            SPListItem newItem = itemsList.Add();

                            newItem["Proveedor"]    = supplierId;
                            newItem["Convocatoria"] = hiringId;

                            try
                            {
                                newItem.Web.AllowUnsafeUpdates = true;
                                newItem.Update();
                            }
                            catch
                            {
                                requestResult = false;
                            }
                            finally
                            {
                                newItem.Web.AllowUnsafeUpdates = false;
                            }
                        }
                        #endregion
                    }
            });

            return(requestResult);
        }
Beispiel #11
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var    web  = SPContext.Current.Site.RootWeb;
            var    list = web.Lists.TryGetList("Laptops");
            var    managedMetaDataField  = list.Fields["brand"] as TaxonomyField;
            var    managedMetaDataField2 = list.Fields["Model"] as TaxonomyField;
            var    termsetId             = managedMetaDataField.TermSetId;
            var    termstoreId           = managedMetaDataField.SspId;
            var    termsetId2            = managedMetaDataField2.TermSetId;
            var    termstoreId2          = managedMetaDataField2.SspId;
            var    taxonomySession       = new TaxonomySession(web.Site);
            var    termstore             = taxonomySession.TermStores[termstoreId];
            var    termstore2            = taxonomySession.TermStores[termstoreId2];
            var    termset   = termstore.GetTermSet(termsetId);
            var    termset2  = termstore2.GetTermSet(termsetId2);
            var    termname  = DDBrand.SelectedValue;
            var    termname2 = DDModel.Text;
            String brand     = DDBrand.SelectedValue;
            String model     = DDModel.Text;
            var    terms     = termset.GetTerms(termname, false);
            var    terms2    = termset2.GetTerms(termname2, false);
            Term   term;
            Term   term2;

            if (terms.Count == 0)
            {
                term = termset.CreateTerm(termname, termstore.Languages[0]);
                termstore.CommitAll();
            }
            else
            {
                term = terms[0];
            }
            if (terms2.Count == 0)
            {
                term2 = termset2.CreateTerm(termname2, termstore2.Languages[0]);
                termstore2.CommitAll();
            }
            else
            {
                term2 = terms2[0];
            }
            SPListItemCollection items = list.Items;
            SPListItem           item  = items.Add();

            item[SPBuiltInFieldId.Title] = "Computer";
            managedMetaDataField.SetFieldValue(item, term);
            managedMetaDataField2.SetFieldValue(item, term2);
            item.Update();
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Computer Added into List')", true);
        }
        /// <summary>
        /// 数据写入活动列表,只写一次.
        /// </summary>
        private void WriteToList(Guid siteID, Guid webID, string lstTitle, Activity myActivity)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPWeb oWebsite = new SPSite(siteID).AllWebs[webID])
                {
                    oWebsite.AllowUnsafeUpdates = true;
                    try
                    {
                        SPList oList   = oWebsite.Lists.TryGetList(lstTitle);
                        string fTaskID = oList.Fields.GetField("计划ID").InternalName;
                        if (ActivityIsExits(oList, fTaskID, myActivity.task.LookupValue) == 1)
                        {
                            return;
                        }

                        string fType     = oList.Fields.GetField("活动类型").InternalName;
                        string fDiDian   = oList.Fields.GetField("活动地点").InternalName;
                        string fObject   = oList.Fields.GetField("活动对象").InternalName;
                        string fStart    = oList.Fields.GetField("开始时间").InternalName;
                        string fDuration = oList.Fields.GetField("持续时长").InternalName;
                        string fAuthor   = oList.Fields.GetField("执行者").InternalName;
                        string fDesc     = oList.Fields.GetField("活动描述").InternalName;

                        SPListItemCollection collItems = oList.Items;
                        SPListItem item = collItems.Add();
                        item["Title"]   = myActivity.name;
                        if (myActivity.start.Year != 1)
                        {
                            item[fStart] = myActivity.start;
                        }
                        item[fDuration] = myActivity.during;
                        item[fDiDian]   = myActivity.aPosition;
                        item[fType]     = myActivity.aType;
                        item[fObject]   = myActivity.aObject;
                        item[fDesc]     = myActivity.aDescption;
                        item[fAuthor]   = myActivity.author;
                        item[fTaskID]   = myActivity.task;
                        item.Update();
                    }
                    catch
                    {
                    }
                    oWebsite.AllowUnsafeUpdates = false;
                }
            });
        }
Beispiel #13
0
        protected void EventGridView_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (e.CommandName.Equals("Insert"))
                        {
                            TextBox txtCBTitle           = (TextBox)EventGridView.FooterRow.FindControl("txtTitle");
                            TextBox txtCBStepTitle       = (TextBox)EventGridView.FooterRow.FindControl("txtStepTitle");
                            TextBox txtCBSStepParameters = (TextBox)EventGridView.FooterRow.FindControl("txtStepParameters");

                            TextBox txtCBLearnerAction = (TextBox)EventGridView.FooterRow.FindControl("txtLearnerAction");
                            TextBox txtCBStepTriggerRoleDistribution = (TextBox)EventGridView.FooterRow.FindControl("txtStepTriggerRoleDistribution");

                            TextBox txtCBStepTime = (TextBox)EventGridView.FooterRow.FindControl("txtStepTime");
                            TextBox txtCBGoStep   = (TextBox)EventGridView.FooterRow.FindControl("txtGoStep");
                            TextBox txtCBGoStepE  = (TextBox)EventGridView.FooterRow.FindControl("txtGoStepE");
                            TextBox txtCBFSID     = (TextBox)EventGridView.FooterRow.FindControl("txtFSID");
                            SPList  list          = web.Lists.TryGetList("EventFlow");
                            // SPListItemCollection coll = list.GetItems();
                            SPListItemCollection myColl = list.Items;
                            SPListItem           item   = myColl.Add();
                            item["Title"]          = txtCBTitle.Text;
                            item["StepTitle"]      = txtCBStepTitle.Text;
                            item["StepParameters"] = txtCBSStepParameters.Text;
                            item["LearnersAction"] = txtCBLearnerAction.Text;
                            item["StepTriggerRoleDistribution"] = txtCBStepTriggerRoleDistribution.Text;
                            item["StepTime"]     = txtCBStepTime.Text;
                            item["IfSoGoToStep"] = txtCBGoStep.Text;
                            item["IfElseToStep"] = txtCBGoStepE.Text;
                            item.Update();
                            Label2.Text       = "Event Flow added, you can add more. Once done Click on Finish";
                            btnFinish.Visible = true;
                        }
                    }
                }
            }


            catch (Exception ex)
            {
                Label1.Text = ex.ToString();
            }
        }
Beispiel #14
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid && ValidateCatpcha())
                {
                    using (SPSite sps = new SPSite(SPContext.Current.Web.Url))
                        using (SPWeb spw = sps.OpenWeb())
                        {
                            SPListItemCollection itemsFormularioContacto = spw.Lists[SAR_LIST].Items;
                            SPListItem           newItem = itemsFormularioContacto.Add();

                            newItem["Title"]                    = txbApellido.Text;
                            newItem["Nombre contacto"]          = txbNombre.Text;
                            newItem["Documento identificación"] = txbCI.Text;
                            newItem["Teléfono contacto"]        = txbTelefono.Text;
                            newItem["Correo contacto"]          = txbCorreo.Text;
                            newItem["País reclamo"]             = txbPais.Text;
                            newItem["Ciudad contacto"]          = txbCiudad.Text;
                            newItem["Fondo inversión"]          = ddlFondo.SelectedValue;
                            newItem["Mensaje contacto"]         = txbMensaje.Text;
                            newItem.Update();

                            //Read the calculated column (Código reclamo)
                            string complaintCode = newItem["Código reclamo"].ToString();

                            //Close the modal dialog. The 'SAR' value is the [returnValue] of the CloseDialogCallback() method of the custom.js
                            this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('SAR" + complaintCode + "');</script>");
                            this.Context.Response.Flush();
                            this.Context.Response.End();
                        }
                }
                else
                {
                    lblCaptcha.Text = "Debe responder correctamente esta prueba.";
                    btnSend.Focus();
                    this.Page.SetFocus(btnSend);
                }
            }
            catch (Exception ex)
            {
                lblCaptcha.Text = ex.Message;
            }
        }
        private static void InsertarNuevoItem()
        {
            using (SPSite sps = new SPSite("http://abastecimiento"))
            {
                using (SPWeb spw = sps.OpenWeb())
                {
                    #region Factura
                    SPListItemCollection listItemsFacturas = spw.Lists["Facturas"].Items;
                    SPListItem           itemFactura       = listItemsFacturas.Add();

                    itemFactura["Num. factura"]  = "(Pre-factura automatica)";
                    itemFactura["Fecha factura"] = DateTime.Today;
                    itemFactura["Total factura"] = 1000;

                    using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                    {
                        itemFactura.SystemUpdate();
                    }
                    #endregion

                    #region Envio
                    SPListItemCollection listItemsEnvios = spw.Lists["Envíos"].Items;
                    SPListItem           itemEnvio       = listItemsEnvios.Add();

                    SPFieldLookupValueCollection facturasAsociadas = new SPFieldLookupValueCollection();
                    facturasAsociadas.Add(new SPFieldLookupValue(itemFactura.ID, itemFactura.Title));

                    itemEnvio["Title"] = "(Pre-envío atomatica)";
                    itemEnvio["Facturas asociadas"] = facturasAsociadas;
                    itemEnvio["Total facturas"]     = itemFactura["Total factura"];

                    using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                    {
                        itemEnvio.SystemUpdate();
                    }
                    #endregion

                    #region ???
                    itemFactura["Envío asociado"] = itemEnvio.ID;
                    #endregion
                }
            }
        }
 public static void addListItem(string listURL, Hashtable keyValuePairTable)
 {
     try
     {
         SPList list = GetListByUrl(listURL);
         SPListItemCollection listItems = list.Items;
         SPListItem           item      = listItems.Add();
         foreach (string key in keyValuePairTable.Keys)
         {
             item[key] = keyValuePairTable.GetProperty(key);
         }
         item.Update();
     }
     catch (Exception ex)
     {
         log.addError(ex.ToString());
         throw;
     }
 }
Beispiel #17
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid && ValidateCatpcha())
                {
                    //NO FUNCIONA EN SANDBOX
                    using (SPSite sps = new SPSite(SPContext.Current.Web.Url))
                        using (SPWeb spw = sps.OpenWeb())
                        {
                            SPListItemCollection itemsFormularioContacto = spw.Lists[CONTACT_LIST].Items;
                            SPListItem           newItem = itemsFormularioContacto.Add();

                            newItem["Title"]             = txbApellido.Text;
                            newItem["Nombre contacto"]   = txbNombre.Text;
                            newItem["Teléfono contacto"] = txbTelefono.Text;
                            newItem["Correo contacto"]   = txbCorreo.Text;
                            newItem["Ciudad contacto"]   = ddlCiudad.SelectedValue;
                            newItem["Zona contacto"]     = txbZona.Text;
                            newItem["Mensaje contacto"]  = txbMensaje.Text;
                            newItem.Update();

                            lblCaptcha.Text = "";

                            //Close the modal dialog. The 'CONTACTO' value is the [returnValue] of the CloseDialogCallback() method of the custom.js
                            this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('CONTACTO');</script>");
                            this.Context.Response.Flush();
                            this.Context.Response.End();
                        }
                }
                else
                {
                    lblCaptcha.Text = "Debe responder correctamente esta prueba.";
                    btnSend.Focus();
                    this.Page.SetFocus(btnSend);
                }
            }
            catch (Exception ex)
            {
                lblCaptcha.Text = "ERROR >> " + ex.Message;
            }
        }
        public SPListItem AdicionaItemLista(string NomeLista, Dictionary <string, object> Valores)
        {
            SPWeb objSite = Site.AllWebs[SPContext.Current.Web.ID];

            SPListItemCollection objLista = objSite.Lists[NomeLista].Items;

            //monta o Item da lista
            SPListItem objItem = objLista.Add();

            //para item no dicionario
            foreach (var i in Valores)
            {
                objItem[i.Key] = i.Value;
            }

            objItem.Web.AllowUnsafeUpdates = true;

            objItem.Update();

            return(objItem);
        }
        //public void updatedatainCEWP(string Cfilename, string DoclibName, string strDivision, string strStateCode, string strFileNamewithoutext)
        //{
        //    string filePath = "/" + ddlDocLibrary.SelectedItem.Text + "/" + Cfilename;
        //    string strCityndCode = strFileNamewithoutext + ", " + strStateCode;
        //    try
        //    {

        //        SPSecurity.RunWithElevatedPrivileges(delegate()
        //        {
        //            SPWeb spWebTest = SPContext.Current.Web;
        //            spWebTest.AllowUnsafeUpdates = true;

        //            using (Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = spWebTest.GetFile(filePath).GetLimitedWebPartManager(PersonalizationScope.Shared))
        //            {

        //                if (mgr != null)
        //                {

        //                    foreach (System.Web.UI.WebControls.WebParts.WebPart part in mgr.WebParts)
        //                    {
        //                        string zoneid = mgr.GetZoneID(part);
        //                        if (zoneid == "Header")
        //                        {

        //                            if (part.GetType().ToString().Equals("Microsoft.SharePoint.WebPartPages.ContentEditorWebPart"))
        //                            {
        //                                ContentEditorWebPart contentEditor = (ContentEditorWebPart)part;

        //                                // create a new XmlElement and put the results there
        //                                XmlDocument xmlDoc = new XmlDocument();
        //                                XmlElement xmlElement = xmlDoc.CreateElement("MyElement");

        //                                string CEWPText = "<div style='text-align: center'><span style='font-family: calibri; color: black; font-size: 18pt; language: en-us'>" +
        //      "<div class='ms-rteFontSize-6' style='text-align: center'><span class='ms-rteFontFace-10' style='color: black; language: en-us'><strong> <span>" +
        //       "<font face='Lucida Console'>" + strDivision + "</font></span></strong></span><span style='font-family: calibri; color: black; language: en-us'><span> </span></span></div>" +
        //      "<div style='text-align: center'><span style='font-family: calibri; color: black; font-size: 18pt; language: en-us'>" + strCityndCode + "</span></div></span></div>";

        //                                xmlElement.InnerText = CEWPText;
        //                                // we MUST set the Content property, not a property of Content.
        //                                contentEditor.Content = xmlElement;

        //                                // persist changes to the database
        //                                mgr.SaveChanges(contentEditor);
        //                            }

        //                        }

        //                    }


        //                }

        //            }

        //        });
        //    }
        //    catch (Exception ex)
        //    {
        //        lblError.Text = filePath + ex.Message + ex.StackTrace + GetFilename(strFileNamewithoutext);
        //    }

        //}

        #region Add Entry to Cities List

        /// <summary>
        ///
        /// </summary>
        private void AddToCitiesList(string cfName)
        {
            try
            {
                SPWeb mySite = SPContext.Current.Web;
                SPListItemCollection listItems = mySite.Lists["Cities"].Items;
                SPListItem           item      = listItems.Add();

                string eName     = cfName;
                string sFilePath = "/" + ddlDocLibrary.SelectedItem.Text + "/" + GetFilename(cfName);

                item["Title"]          = eName;
                item["EntityName"]     = eName;
                item["StateName"]      = ddlState.SelectedItem.Text.ToString();
                item["NavigationLink"] = sFilePath;

                item.Update();
            }
            catch (Exception ex)
            {
                lblMsg.Text = string.Format("Error : {0} - Stack Trace : {1}", ex.Message, ex.StackTrace);
            }
        }
        static void Main(string[] args)
        {
            SPSite sitio = null;
            SPWeb  web   = null;

            string urlSitio;
            string nombreLista;
            int    idInicio;

            try
            {
                #region Toma de datos
                Console.WriteLine("Este programa permite iniciar una determinada " +
                                  "lista con un valor ID definido.");
                Console.WriteLine();

                Console.Write("Ingrese la URL del sitio: ");
                urlSitio = Console.ReadLine();

                Console.Write("Ingrese el nombre de la lista: ");
                nombreLista = Console.ReadLine();

                Console.Write("Ingrese el ID de inicio: ");
                idInicio = Convert.ToInt16(Console.ReadLine());
                #endregion

                #region Consulta SP
                sitio = new SPSite(urlSitio);
                web   = sitio.OpenWeb();

                SPList lista = web.Lists[nombreLista];
                SPListItemCollection itemsAntes = lista.Items;

                if (itemsAntes.Count == 0)
                {
                    #region Crear items
                    for (int i = 1; i < idInicio; i++)
                    {
                        SPListItem item = itemsAntes.Add();
                        item["Title"] = "Item " + i;
                        item.Update();
                    }
                    #endregion

                    #region Eliminar items
                    SPListItemCollection itemsDespues = lista.Items;
                    StringBuilder        batchString  = new StringBuilder();
                    batchString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                    foreach (SPListItem item in itemsDespues)
                    {
                        batchString.Append("<Method>");
                        batchString.Append("<SetList Scope=\"Request\">" + Convert.ToString(item.ParentList.ID) + "</SetList>");
                        batchString.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
                        batchString.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
                        batchString.Append("</Method>");
                    }
                    batchString.Append("</Batch>");
                    web.ProcessBatchData(batchString.ToString());

                    // Eliminar papelera
                    sitio.RecycleBin.DeleteAll();

                    Console.WriteLine("Proceso completado exitosamente.");
                    #endregion
                }
                else
                {
                    Console.WriteLine("Este proceso solo puede ser aplicado " +
                                      "a una lista que no contenga items.");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine("Se produjo un error vuelva a intentarlo.");
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (web != null)
                {
                    web.Dispose();
                }
                if (sitio != null)
                {
                    sitio.Dispose();
                }
            }
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    string newItemId = "";

                    using (SPSite sps = new SPSite(SPContext.Current.Web.Url))
                        using (SPWeb spw = sps.OpenWeb())
                        {
                            SPListItemCollection itemsAdvertisingRecords = spw.Lists[ADVERTISING_RECORDS].Items;
                            SPListItem           newItem = itemsAdvertisingRecords.Add();

                            List <string> sendMailResponce = new List <string>(2);

                            System.Web.UI.WebControls.DropDownList officeElement =
                                new System.Web.UI.WebControls.DropDownList();
                            string nameBox;
                            string phoneBox;
                            if (SpAdvertisingTemplate == Templates.Plantilla_A)
                            {
                                officeElement = ddlOfficeA;
                                nameBox       = txbNameA.Text;
                                phoneBox      = txbPhoneA.Text;
                            }
                            else
                            {
                                officeElement = ddlOfficeB;
                                nameBox       = txbNameB.Text;
                                phoneBox      = txbPhoneB.Text;
                            }

                            sendMailResponce = this.SendMail(
                                spw, officeElement.SelectedIndex - 1, nameBox, phoneBox);

                            newItem["Title"] = nameBox;
                            newItem["T_x00ed_tulo_x0020_Campa_x00f1_a"] = spw.Lists[ADVERTISING_PARAMETERS].GetItemById(SpAdvertisingId).Title;
                            newItem["Tel_x00e9_fono_x0020_Registro"]    = phoneBox;
                            newItem["Agencia_x0020_Registro"]           = officeElement.SelectedItem.Value + " | " + officeElement.SelectedItem.Text;
                            newItem["Correo_x0020_Enviado"]             = Convert.ToBoolean(sendMailResponce[0]);
                            newItem["Comentarios_x0020_Registro"]       = sendMailResponce[1];

                            newItem.Update();
                            newItemId = newItem.ID.ToString();
                        }

                    Page.Response.Redirect(SpAdvertisingRedirect + "?ad=" + SpAdvertisingId + "&cl=" + newItemId, true);
                }
            }
            catch (Exception ex)
            {
                //pnlFormA.Visible = false;
                //pnlFormB.Visible = false;
                System.Web.UI.LiteralControl deadlineMessage = new System.Web.UI.LiteralControl();
                deadlineMessage.Text =
                    "<link rel='stylesheet' href='/_catalogs/masterpage/bmsc/styles/advertising_a.css'>" +
                    "<div class='advertisingMessage'>" + ex.Message + "</div>";

                this.Controls.Clear();
                this.Controls.Add(deadlineMessage);
            }
        }
        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid && this.IsCaptchaValid())
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite sps = new SPSite(SPContext.Current.Web.Url))
                            using (SPWeb spw = sps.OpenWeb())
                            {
                                SPListItemCollection itemsList = spw.Lists[LIST_SUPPLIERS].Items;
                                SPListItem newItem             = itemsList.Add();

                                newItem["Tipo_x0020_empresa"] = ddlType.SelectedItem.Text;
                                newItem["Title"]                             = txbName.Text.Trim();
                                newItem["NIT"]                               = txbCi.Text.Trim();
                                newItem["Direcci_x00f3_n"]                   = txbAddress.Text.Trim();
                                newItem["Correo"]                            = txbMail.Text.Trim();
                                newItem["Tel_x00e9_fonos"]                   = txbPhones.Text.Trim();
                                newItem["Correo_x0020_e_x002e_"]             = txbEmail.Text.Trim();
                                newItem["P_x00e1_gina_x0020_web"]            = string.IsNullOrWhiteSpace(txbWebsite.Text) ? "" : txbWebsite.Text.Trim();
                                newItem["Nombre_x0020_rep_x002e__x0020_le"]  = txbLegal1.Text.Trim();
                                newItem["Cargo_x0020_rep_x002e__x0020_leg"]  = txbLegal2.Text.Trim();
                                newItem["Correo_x0020_rep_x002e__x0020_le"]  = txbLegal3.Text.Trim();
                                newItem["Tel_x00e9_fonos_x0020_rep_x002e_"]  = txbLegal4.Text.Trim();
                                newItem["Prod_x002e__x0020_serv_x002e__x0"]  = ddlServiceGen1.SelectedItem.Text;
                                newItem["Prod_x002e__x0020_serv_x002e__x01"] = ddlServiceGen2.SelectedItem.Text;
                                newItem["Prod_x002e__x0020_serv_x002e__x00"] = txbServiceSpe.Text.Trim();

                                string selectedCities = ";#";
                                foreach (ListItem item in cblCity.Items)
                                {
                                    if (item.Selected)
                                    {
                                        selectedCities += item.Value + ";#";
                                    }
                                }
                                newItem["_x00c1_mbito"] = selectedCities;

                                newItem["Banco"]               = txbBank1.Text.Trim();
                                newItem["Beneficiario"]        = txbBank2.Text.Trim();
                                newItem["Cuenta_x0020_pago"]   = txbBank3.Text.Trim();
                                newItem["Cuenta_x0020_moneda"] = ddlBank4.SelectedValue;

                                if (file1.HasFile)
                                {
                                    newItem.Attachments.Add("1_testimonio_constitucion.pdf", file1.FileBytes);
                                }
                                if (file2.HasFile)
                                {
                                    newItem.Attachments.Add("2_poder_representante.pdf", file2.FileBytes);
                                }
                                if (file3.HasFile)
                                {
                                    newItem.Attachments.Add("3_matricula_comercio.pdf", file3.FileBytes);
                                }
                                if (file4.HasFile)
                                {
                                    newItem.Attachments.Add("4_nit.pdf", file4.FileBytes);
                                }
                                newItem.Attachments.Add("5_ci_representante.pdf", file5.FileBytes);
                                newItem.Attachments.Add("6_formulario_registro.pdf", file6.FileBytes);

                                try
                                {
                                    newItem.Web.AllowUnsafeUpdates = true;
                                    newItem.Update();
                                }
                                finally
                                {
                                    newItem.Web.AllowUnsafeUpdates = false;
                                }
                            }
                    });

                    lblError.Text = "";
                    Page.Response.Redirect("/Paginas/Formularios/ProveedoresConfirmacion.aspx", true);
                }
                else
                {
                    lblError.Text = "<p>* al parecer eres un robot, ya que no pasaste la prueba.</p>";
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
Beispiel #23
0
        private void AddNewContact()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.ID))
                {
                    //SPWeb web = SPContext.Current.Site.RootWeb;
                    SPWeb web = elevatedSite.RootWeb;
                    web.AllowUnsafeUpdates = true;
                    try
                    {
                        SPList lst = web.Lists["Contact Forms"];
                        SPListItemCollection items = GetEmptyItemsCollection(lst);

                        SPContentTypeId ctid = lst.ContentTypes.BestMatch(new SPContentTypeId("0x0100548398963F53464698001F990988DBA7"));

                        SPListItem item = items.Add();
                        item[SPBuiltInFieldId.ContentTypeId] = ctid;
                        item[SPBuiltInFieldId.Title]         = this.Context.Server.HtmlEncode(txtFullName.Text);
                        item[SPBuiltInFieldId.WorkAddress]   = string.Format("{0} {1}", this.Context.Server.HtmlEncode(txtStreet.Text), this.Context.Server.HtmlEncode(txtStreetNo.Text));
                        item[SPBuiltInFieldId.WorkCity]      = this.Context.Server.HtmlEncode(txtCity.Text);
                        item[SPBuiltInFieldId.WorkZip]       = this.Context.Server.HtmlEncode(txtZipCode.Text);
                        item[SPBuiltInFieldId.EMail]         = this.Context.Server.HtmlEncode(txtEMail.Text);
                        item[SPBuiltInFieldId.HomePhone]     = this.Context.Server.HtmlEncode(txtPhone.Text);

                        //SPFieldMultiChoiceValue val = new SPFieldMultiChoiceValue();
                        //if (cbContactByEmail.Checked) val.Add(Core.Utils.GetLocString("FLDContactByEmail"));
                        //if (cbContactByPhone.Checked) val.Add(Core.Utils.GetLocString("FLDContactByPhone"));

                        item[ContactBy_Id] = "By e-mail";
                        item[ContactBankCooperation_Id] = rbPartener.SelectedValue; //rbPartenerYes.Checked;
                        item[ContactInterestedFor_Id]   = ddlInterestedIn.SelectedItem.Value;
                        item[ContactSubject_Id]         = this.Context.Server.HtmlEncode(txtBody.Text);

                        item.Update();//storing
                        SubmitResultPanel.Visible = true;
                        StatusLabel.Text          = "<div class=\"sub_success\">" + Core.Utils.GetLocString("loanformsubmissionsalut") + "<br /><br />" + Core.Utils.GetLocString("loanformsubmissionbody");
                        StatusLabel.Text         += "<br /><br />" + Core.Utils.GetLocString("FormThankYou") + "<br /><br />";
                        StatusLabel.Text         += Core.Utils.GetLocString("Menunbgbank") + "<br />";
                        StatusLabel.Text         += Core.Utils.GetLocString("FormSignature") + "<br />";
                        StatusLabel.Text         += "</div>";
                        FormPanel.Visible         = false;

                        //send email
                        string emailAddresses = Core.Configuration.GetValue1(SPContext.Current.Site.RootWeb, Core.Configuration.ConfigurationKeys.FormContact, Core.Configuration.ConfigurationCategories.Data);
                        string emailUser      = item[SPBuiltInFieldId.EMail] as string;
                        if (string.IsNullOrEmpty(emailUser))
                        {
                            emailUser = item[SPBuiltInFieldId.Email2] as string;
                        }
                        if (!string.IsNullOrEmpty(emailAddresses))
                        {
                            // Expected format for emailAddresses: [email protected];[email protected]

                            string emailSubject     = Core.Configuration.GetValue2(SPContext.Current.Site.RootWeb, Core.Configuration.ConfigurationKeys.FormContact, Core.Configuration.ConfigurationCategories.Data);
                            string emailAddressFrom = Core.Configuration.GetValue1(SPContext.Current.Site.RootWeb, Core.Configuration.ConfigurationKeys.FormEMailFrom, Core.Configuration.ConfigurationCategories.Data);

                            if (string.IsNullOrEmpty(emailAddressFrom))
                            {
                                emailAddressFrom = "*****@*****.**";
                            }
                            if (string.IsNullOrEmpty(emailSubject))
                            {
                                emailSubject = Core.Utils.GetLocString("contactEmailSubject");
                            }

                            List <string> emailAddressesList = new List <string>();
                            emailAddressesList.AddRange(emailAddresses.Split(new char[] { ';' }));
                            List <string> lm = new List <string>();
                            if (!string.IsNullOrWhiteSpace(emailUser))
                            {
                                lm.Add(emailUser);
                            }

                            //List<string> lm1 = new List<string>();
                            //lm1.Add("*****@*****.**");
                            Core.EMails.NotifyNewContactRegistration(web, item, emailSubject, lm, emailAddressesList, null, emailAddressFrom);
                        }
                    }
                    catch (Exception ex)//uls
                    {
                        Logger.LogEvent(string.Format(Core.Configuration.ERROR_STRING_FORMAT, null, "ContactForm.AddNewContact", null, ex.ToString()), System.Diagnostics.EventLogEntryType.Error);
                        SubmitResultPanel.Visible = true;
                        StatusLabel.Text          = "σφαλμα αποστολής";
                        FormPanel.Visible         = false;
                    }
                    finally
                    {
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
        public override void Execute(Guid targetInstanceId)
        {
            string webUrl = "https://portaladp/";

            using (SPWeb oWebsite = new SPSite(webUrl).OpenWeb())
            {
                oWebsite.AllowUnsafeUpdates = true;


                SPList lista = oWebsite.Lists["Directorio Telefónico AdP"];

                SPListItemCollection spcollLista  = lista.Items;
                SPListItemCollection spcollLista1 = lista.Items;


                List <Usuario>   listaUsuariosAD     = new List <Usuario>();
                List <Usuario>   listaUsuariosPortal = new List <Usuario>();
                DirectoryContext dc     = new DirectoryContext(DirectoryContextType.Domain, Environment.UserDomainName);
                Domain           domain = Domain.GetDomain(dc);
                DirectoryEntry   de     = domain.GetDirectoryEntry();

                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(objectClass=user)(objectCategory=person)(mail=*))";

                deSearch.PropertiesToLoad.Add("mail");
                SearchResult result = deSearch.FindOne();

                SearchResultCollection results = deSearch.FindAll();

                // Obtenemos todos los usuarios del AD
                foreach (SearchResult srUser in results)
                {
                    DirectoryEntry deUser = srUser.GetDirectoryEntry();

                    using (new SPMonitoredScope("Get displayName and company and l and title and facsimileTelephoneNumber and telephoneNumber and homePhone and mobile and objectClass From AD"))
                    {
                        Usuario user = new Usuario();
                        if (deUser.InvokeGet("displayName") == null)
                        {
                            user.displayName = "";
                        }
                        else
                        {
                            user.displayName = deUser.InvokeGet("displayName").ToString();
                        }

                        if (deUser.InvokeGet("company") == null)
                        {
                            user.company = "";
                        }
                        else
                        {
                            user.company = deUser.InvokeGet("company").ToString();
                        }

                        if (deUser.InvokeGet("L") == null)
                        {
                            user.l = "";
                        }
                        else
                        {
                            user.l = deUser.InvokeGet("l").ToString();
                        }

                        if (deUser.InvokeGet("title") == null)
                        {
                            user.title = "";
                        }
                        else
                        {
                            user.title = deUser.InvokeGet("title").ToString();
                        }
                        if (deUser.InvokeGet("facsimileTelephoneNumber") == null)
                        {
                            user.facsimileTelephoneNumber = "";
                        }
                        else
                        {
                            user.facsimileTelephoneNumber = deUser.InvokeGet("facsimileTelephoneNumber").ToString(); // anexo 513 nortel
                        }
                        if (deUser.InvokeGet("telephoneNumber") == null)
                        {
                            user.telephoneNumber = "";
                        }
                        else
                        {
                            user.telephoneNumber = deUser.InvokeGet("telephoneNumber").ToString(); // anexo 513 nortel
                        }
                        if (deUser.InvokeGet("homePhone") == null)
                        {
                            user.homePhone = "";
                        }
                        else
                        {
                            user.homePhone = deUser.InvokeGet("homePhone").ToString(); // cel completo
                        }
                        if (deUser.InvokeGet("mobile") == null)
                        {
                            user.mobile = "";
                        }
                        else
                        {
                            user.mobile = deUser.InvokeGet("mobile").ToString(); // rpm
                        }
                        if (deUser.InvokeGet("mail") == null)
                        {
                            user.mobile = "";
                        }
                        else
                        {
                            user.email = deUser.InvokeGet("mail").ToString();
                        }
                        // obtener DNI
                        if (deUser.InvokeGet("pager") == null)
                        {
                            user.pager = "";
                        }
                        else
                        {
                            user.pager = deUser.InvokeGet("pager").ToString();
                        }



                        listaUsuariosAD.Add(user);
                    }
                }

                // obtener usuarios Portal

                foreach (SPListItem item in spcollLista)
                {
                    Usuario user = new Usuario();
                    if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                    {
                    }
                    else
                    {
                        if (item["ows_Title"] == null || item["ows_Title"].ToString() == "")
                        {
                            user.displayName = "";
                        }
                        else
                        {
                            user.displayName = item["ows_Title"].ToString();
                        }
                        //if (item["ows_Company"] == null || item["ows_Company"].ToString() == "")
                        //{
                        //    user.company = "";
                        //}
                        //else
                        //{
                        //    user.company = item["ows_Company"].ToString();
                        //}

                        if (item["ows_WorkPhone"] == null || item["ows_WorkPhone"].ToString() == "")
                        {
                            user.facsimileTelephoneNumber = "";
                        }
                        else
                        {
                            user.facsimileTelephoneNumber = item["ows_WorkPhone"].ToString();
                        }
                        if (item["ows_CellPhone"] == null || item["ows_CellPhone"].ToString() == "")
                        {
                            user.homePhone = "";
                        }
                        else
                        {
                            user.homePhone = item["ows_CellPhone"].ToString();
                        }
                        if (item["ows_HomePhone"] == null || item["ows_HomePhone"].ToString() == "")
                        {
                            user.mobile = "";
                        }
                        else
                        {
                            user.mobile = item["ows_HomePhone"].ToString();
                        }
                        if (item["ows_WorkCity"] == null || item["ows_WorkCity"].ToString() == "")
                        {
                            user.l = "";
                        }
                        else
                        {
                            user.l = item["ows_WorkCity"].ToString();
                        }
                        if (item["ows_JobTitle"] == null || item["ows_JobTitle"].ToString() == "")
                        {
                            user.title = "";
                        }
                        else
                        {
                            user.title = item["ows_JobTitle"].ToString();
                        }
                        if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                        {
                            user.email = "";
                        }
                        else
                        {
                            user.email = item["ows_Email"].ToString();
                        }
                        listaUsuariosPortal.Add(user);
                        //DNI
                        if (item["ows_PagerNumber"] == null || item["ows_PagerNumber"].ToString() == "")
                        {
                            user.pager = "";
                        }
                        else
                        {
                            user.pager = item["ows_PagerNumber"].ToString();
                        }
                        listaUsuariosPortal.Add(user);
                    }
                }


                // Actualiza todos los Items de la Lista DIrectorio Telefonico!
                foreach (Usuario user in listaUsuariosAD)
                {
                    foreach (SPListItem item in spcollLista)
                    {
                        if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                        {
                        }
                        else
                        {
                            if (string.Compare(user.email.ToString(), item["ows_Email"].ToString(), true) == 0)
                            {
                                if (item["ows_Title"] == null || item["ows_Title"].ToString() != user.displayName.ToString())
                                {
                                    item["ows_Title"] = user.displayName.ToString(); // Nombre
                                    item.Update();
                                }
                                //if (item["ows_Company"] == null || item["ows_Company"].ToString() != user.company.ToString())
                                //{
                                //    item["ows_Company"] = user.company.ToString(); // Empresa
                                //    item.Update();
                                //}

                                if (item["ows_WorkPhone"] == null || item["ows_WorkPhone"].ToString() != user.facsimileTelephoneNumber.ToString())
                                {
                                    if (user.facsimileTelephoneNumber != "" && user.telephoneNumber != "")
                                    {
                                        item["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString() + " / " + user.telephoneNumber.ToString(); // Fijo
                                        item.Update();
                                    }
                                    else if (user.facsimileTelephoneNumber != "" && user.telephoneNumber == "")
                                    {
                                        item["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString(); // Fijo
                                        item.Update();
                                    }
                                    else if (user.facsimileTelephoneNumber == "" && user.telephoneNumber != "")
                                    {
                                        item["ows_WorkPhone"] = user.telephoneNumber.ToString(); // Fijo
                                        item.Update();
                                    }
                                }

                                if (item["ows_CellPhone"] == null || item["ows_CellPhone"].ToString() != user.homePhone.ToString())
                                {
                                    item["ows_CellPhone"] = user.homePhone.ToString(); // movil
                                    item.Update();
                                }

                                if (item["ows_HomePhone"] == null || item["ows_HomePhone"].ToString() != user.mobile.ToString())
                                {
                                    item["ows_HomePhone"] = user.mobile.ToString(); // rpm
                                    item.Update();
                                }
                                //if (item["ows_WorkCity"] == null || item["ows_WorkCity"].ToString() != user.l.ToString())
                                //{
                                //    item["ows_WorkCity"] = user.l.ToString(); // ubicacion
                                //    item.Update();
                                //}
                                if (item["ows_JobTitle"] == null || item["ows_JobTitle"].ToString() != user.title.ToString())
                                {
                                    item["ows_JobTitle"] = user.title.ToString(); // cargo
                                    item.Update();
                                }

                                if (item["ows_PagerNumber"] == null || item["ows_PagerNumber"].ToString() != user.pager.ToString())
                                {
                                    item["ows_PagerNumber"] = user.pager.ToString(); // DNI
                                    item.Update();
                                }
                                break;
                            }
                        }
                    }
                }

                // Capturamos los datos de la lista [Lista de Trabajadores] de RRHH
                String        sSel = "select DNI,PUESTO_TRABAJO from V_TrabajadoresADP";
                SqlConnection sCnn =
                    new SqlConnection("data source = 192.168.57.19; initial catalog = OFIPLAN; user id = sharepoint; password = 5h4r3p01nt#");

                SqlDataAdapter da = new SqlDataAdapter(sSel, sCnn);
                DataTable      dt = new DataTable();

                da.Fill(dt);

                List <Usuario> usuarios = new List <Usuario>();

                foreach (DataRow dr in dt.Rows)
                {
                    Usuario usuario = new Usuario();
                    string  DNI     = (string)dr["DNI"];
                    string  Puesto  = (string)dr["PUESTO_TRABAJO"];

                    usuario.pager = DNI;
                    usuario.title = Puesto;

                    usuarios.Add(usuario);
                }


                // Actualiza todos los cargos de la Lista DIrectorio Telefonico!

                try
                {
                    foreach (Usuario user in usuarios)
                    {
                        foreach (SPListItem item in spcollLista)
                        {
                            if (item["ows_Email"] == null || item["ows_Email"].ToString() == "")
                            {
                            }
                            else
                            {
                                if (item["ows_PagerNumber"] != null)
                                {
                                    if (string.Compare(user.pager.ToString().Trim(), item["ows_PagerNumber"].ToString().Trim(), true) == 0)
                                    {
                                        if (item["ows_JobTitle"] == null || item["ows_JobTitle"].ToString() != user.title.ToString())
                                        {
                                            item["ows_JobTitle"] = user.title.ToString();     // cargo
                                            item.Update();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // error creating job
                    using (EventLog eventLog = new EventLog("Application"))
                    {
                        eventLog.Source = "Application";
                        eventLog.WriteEntry("Error en actualización: " + ex.Message.ToString() + " \n " + ex.Data.ToString(), EventLogEntryType.Error, 6666, 1);
                    }
                }


                foreach (Usuario user in listaUsuariosAD)
                {
                    if (user.email.ToString() != "")
                    {
                        if ((verificarExiste(user.email.ToString(), listaUsuariosPortal) == false) && (user.telephoneNumber != "" || user.facsimileTelephoneNumber != "" || user.homePhone != "" || user.mobile != ""))
                        //if ((verificarExiste(user.email.ToString(), listaUsuariosPortal) == false) )
                        {
                            SPListItem item1 = spcollLista.Add();

                            item1["ows_Title"] = user.displayName.ToString();
                            //item1["ows_Company"] = user.company.ToString();
                            if (user.facsimileTelephoneNumber != "" && user.telephoneNumber != "")
                            {
                                item1["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString() + " / " + user.telephoneNumber.ToString(); // Fijo
                            }
                            else if (user.facsimileTelephoneNumber != "" && user.telephoneNumber == "")
                            {
                                item1["ows_WorkPhone"] = user.facsimileTelephoneNumber.ToString(); // Fijo
                            }
                            else if (user.facsimileTelephoneNumber == "" && user.telephoneNumber != "")
                            {
                                item1["ows_WorkPhone"] = user.telephoneNumber.ToString(); // Fijo
                            }

                            item1["ows_CellPhone"] = user.homePhone.ToString();
                            item1["ows_HomePhone"] = user.mobile.ToString();
                            //item1["ows_WorkCity"] = user.l.ToString();
                            //item1["ows_JobTitle"] = user.title.ToString();
                            item1["ows_Email"]       = user.email.ToString();
                            item1["ows_PagerNumber"] = user.pager.ToString();
                            item1.Update();
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                    }
                }
                oWebsite.AllowUnsafeUpdates = false;
            }
        }
        /// <summary>
        /// Crear una copia del item con la columna 'Cantidad' modificada segun la
        /// ingresada por el usuario
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSepararItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    SPListItemCollection itemsPedidos    = listaItemsPedidos.Items;
                    SPListItem           nuevoItemPedido = itemsPedidos.Add();

                    #region Crear copia del ítem
                    string[] arrTitulo = itemPedido.Title.Split(new string[] { ";#" }, StringSplitOptions.None);
                    if (arrTitulo.Length == 1)
                    {
                        string titulo = itemPedido.Title + ";#1";
                        nuevoItemPedido["Title"] = titulo;
                    }
                    else
                    {
                        string titulo = arrTitulo[0] + ";#" +
                                        (int.Parse(arrTitulo[arrTitulo.Length - 1]) + 1).ToString();
                        nuevoItemPedido["Title"] = titulo;
                    }
                    nuevoItemPedido["OCI asociada"] = itemPedido["OCI asociada"];
                    //nuevoItemPedido["Factura asociada"] = itemPedido["Factura asociada"];
                    nuevoItemPedido["Ítem asociado"]    = itemPedido["Ítem asociado"];
                    nuevoItemPedido["Precio unitario"]  = itemPedido["Precio unitario"];
                    nuevoItemPedido["Peso"]             = itemPedido["Peso"];
                    nuevoItemPedido["Unidad medida"]    = itemPedido["Unidad medida"];
                    nuevoItemPedido["Dimensiones"]      = itemPedido["Dimensiones"];
                    nuevoItemPedido["País origen"]      = itemPedido["País origen"];
                    nuevoItemPedido["Cliente"]          = itemPedido["Cliente"];
                    nuevoItemPedido["Cliente asociado"] = itemPedido["Cliente asociado"];
                    nuevoItemPedido["Estado pedido"]    = itemPedido["Estado pedido"];
                    nuevoItemPedido["Tipo pedido"]      = itemPedido["Tipo pedido"];
                    //nuevoItemPedido["Tipo pago"] = itemPedido["Tipo pago"];
                    nuevoItemPedido["Fecha prevista llegada"] = itemPedido["Fecha prevista llegada"];
                    nuevoItemPedido["Observaciones"]          = "Copia de ítem " + itemPedido.Title + " (ID " + itemPedido.ID + ").";
                    nuevoItemPedido["Cantidad"] = int.Parse(txbCantidad.Text);

                    nuevoItemPedido.Update();
                    #endregion

                    #region Actualizar ítem original
                    itemPedido["Cantidad"] = cantidadOriginal - int.Parse(txbCantidad.Text);

                    itemPedido.Update();
                    #endregion

                    #region Relacionar ítem copiado
                    Abastecimiento.EjecutorOperacionesSP.RelacionarItemCopiadoConOCP(itemPedido, nuevoItemPedido);
                    #endregion

                    this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                    this.Context.Response.Flush();
                    this.Context.Response.End();
                }
            }
            catch (Exception ex)
            {
                ltlResultados.Text = ex.Message;
            }
        }