private void Edit(Project pro)
        {
            if (oList != null)
            {
                // Edit
                if (pro.Id != 0)
                {
                    // Assume there is a list item with ID=1.
                    ListItem listItem = oList.GetItemById(pro.Id);
                    // Write a new value to the Body field of the Announcement item.
                    listItem["ProjectName"]     = pro.ProjectName;
                    listItem["ProjDescription"] = pro.Description;
                    listItem["StartDate"]       = pro.StartDate;
                    listItem["_EndDate"]        = pro.EndDate;
                    listItem["State"]           = pro.State;

                    // Leader
                    FieldLookupValue lookup = new FieldLookupValue();
                    lookup.LookupId    = 3;
                    listItem["Leader"] = lookup;

                    // Members
                    List <FieldLookupValue> lvList = new List <FieldLookupValue>();
                    lvList.Add(lookup);
                    lvList.Add(new FieldLookupValue()
                    {
                        LookupId = 1
                    });
                    listItem["Member"] = lvList;
                    listItem.Update();
                    context.ExecuteQuery();

                    context.ExecuteQuery();
                }
                // Add new item
                else
                {
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem newItem = oList.AddItem(itemCreateInfo);
                    newItem["Title"]           = Guid.NewGuid();
                    newItem["ProjectName"]     = pro.ProjectName;
                    newItem["ProjDescription"] = pro.Description;
                    newItem["StartDate"]       = pro.StartDate;
                    newItem["_EndDate"]        = pro.EndDate;
                    newItem["State"]           = pro.State;
                    newItem.Update();

                    context.ExecuteQuery();
                }
            }
        }
Exemple #2
0
 private void CreateNovoContacto(ClientContext siteContexto, List listaTelefonica, ItemListaTelefonicaProperties itemListaTelefonicaProperties)
 {
     try
     {
         ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
         ListItem addItem = listaTelefonica.AddItem(itemCreateInfo);
         addItem["Title"]       = itemListaTelefonicaProperties.PreferredName;
         addItem["FirstName"]   = itemListaTelefonicaProperties.FirstName;
         addItem["LastName"]    = itemListaTelefonicaProperties.LastName;
         addItem["Email"]       = itemListaTelefonicaProperties.Email;
         addItem["PagerNumber"] = itemListaTelefonicaProperties.Pager;
         addItem["Department"]  = itemListaTelefonicaProperties.Department;
         addItem["CellPhone"]   = itemListaTelefonicaProperties.CellPhone;
         addItem["PictureURL"]  = itemListaTelefonicaProperties.PictureURL;
         addItem["Office"]      = itemListaTelefonicaProperties.Office;
         addItem["WorkFax"]     = itemListaTelefonicaProperties.WorkFax;
         addItem["WorkPhone"]   = itemListaTelefonicaProperties.WorkPhone;
         addItem["WorkState"]   = itemListaTelefonicaProperties.WorkState;
         addItem["WorkCity"]    = itemListaTelefonicaProperties.WorkCity;
         addItem["WorkCountry"] = itemListaTelefonicaProperties.WorkCountry;
         addItem["WorkZip"]     = itemListaTelefonicaProperties.WorkZip;
         addItem["IpPhone"]     = itemListaTelefonicaProperties.IpPhone;
         addItem["WorkAddress"] = itemListaTelefonicaProperties.WorkAddress;
         addItem["AboutMe"]     = itemListaTelefonicaProperties.AboutMe;
         addItem["JobTitle"]    = itemListaTelefonicaProperties.JobTitle;
         addItem["Company"]     = itemListaTelefonicaProperties.Company;
         addItem.Update();
         siteContexto.ExecuteQuery();
     }
     catch (Exception ex)
     {
         _log.Error($"-> CreateNovoContacto no processo: SharepointSyncJob: {ex}", ex);
     }
 }
Exemple #3
0
        private void ProductEditorDialog_AddClosed(object sender, EventArgs e)
        {
            ProductEditor dialog = (ProductEditor)sender;

            // stop if they clicked cancel
            if (dialog.DialogResult == false)
            {
                return;
            }

            StatusBarPanel.BeginUpdateMessage("Creating new item...");

            SP.List products = Globals.ClientContext.Web.Lists.GetByTitle("Products");
            SP.ListItemCreationInformation newProductInfo = new SP.ListItemCreationInformation();

            SP.ListItem newProduct = products.AddItem(newProductInfo);
            newProduct["Title"] = dialog.ProductNameTextBox.Text;
            newProduct["Product_x0020_Number"] = dialog.ProductNumberTextBox.Text;
            newProduct["Price"] = dialog.ProductPriceTextBox.Text;
            SP.FieldLookupValue fieldValue = new SP.FieldLookupValue();
            foreach (SP.ListItem item in Globals.ProductCategories)
            {
                if (item["Title"].ToString() == ((SP.ListItem)dialog.ProductCategoryComboBox.SelectedItem)["Title"].ToString())
                {
                    fieldValue.LookupId = item.Id;
                }
            }
            newProduct["Category"] = fieldValue;

            newProduct.Update();
            Globals.ClientContext.ExecuteQuery();

            this.Dispatcher.BeginInvoke(new Action(OnProducteditorAddUIUpdater), DispatcherPriority.Normal);
        }
        public int InsertEntry(EmployeeModel emp, string siteUrl)
        {
            try{
                using (MSC.ClientContext context = GetContext(siteUrl))
                {
                    MSC.List list = context.Web.Lists.GetByTitle("TIM_DailyAttendance");

                    MSC.ListItem listItem = null;

                    MSC.ListItemCreationInformation itemCreateInfo = new MSC.ListItemCreationInformation();
                    listItem = list.AddItem(itemCreateInfo);

                    listItem["AttendanceDate"] = Convert.ToDateTime(emp.attendance_date).ToString("dd-MM-yyyy");
                    listItem["CheckinTime"]    = emp.checkin_time;
                    listItem["CheckoutTime"]   = emp.checkout_time;
                    listItem["Comment"]        = emp.comment;
                    listItem["EmpNo"]          = emp.empno;
                    listItem["Hours"]          = emp.hours;
                    listItem["EmpName"]        = emp.name;
                    listItem["EmpMail"]        = emp.office_email;
                    listItem.Update();
                    context.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
            }

            return(0);
        }
Exemple #5
0
        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();
        }
Exemple #6
0
        public async Task <bool> AddItemToList(string listName, SharepointListItem item)
        {
            try
            {
                // Authentication.
                using (var context = GetSharepointSiteContext())
                {
                    Microsoft.SharePoint.Client.List eventList = context.Web.Lists.GetByTitle(listName);
                    ListItemCreationInformation      itemInfo  = new ListItemCreationInformation();

                    ListItem listItemToAdd = eventList.AddItem(itemInfo);
                    foreach (var field in item)
                    {
                        listItemToAdd[field.Key] = field.Value;
                    }
                    listItemToAdd.Update();
                    await context.ExecuteQueryAsync();

                    return(true);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An unexpected error occurred while adding an item.");
                Console.WriteLine(e.Message);
                return(false);
            }
        }
        private void createButton_Click(object sender, RoutedEventArgs e)
        {
            string        UserName = "******", Password = "******";
            ClientContext ctx      = new ClientContext("https://omisayeduiu.sharepoint.com/sites/sayeddev");
            SecureString  passWord = new SecureString();

            foreach (char c in Password.ToCharArray())
            {
                passWord.AppendChar(c);
            }
            ctx.Credentials = new SharePointOnlineCredentials(UserName, passWord);


            Web myWeb = ctx.Web;

            Microsoft.SharePoint.Client.List sectionsList = myWeb.Lists.GetByTitle("sectionInfo");

            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

            Microsoft.SharePoint.Client.ListItem newItem = sectionsList.AddItem(itemCreateInfo);
            newItem["sectionName"]   = sectionBox.Text.Trim().ToString();
            newItem["sectionWeight"] = Convert.ToInt32(weightBox.Text.Trim());
            newItem.Update();

            ctx.ExecuteQuery();

            this.show();
        }
Exemple #8
0
        public void InsertarElemento(Persona persona, HttpContextBase HttpContext)
        {
            //string siteUrl = "https://latinshare.sharepoint.com/sites/dev/";
            //ClientContext clientContext = new ClientContext(siteUrl);
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            //var creds = new SharePointOnlineCredentials("*****@*****.**", password); // Requires SecureString() for password
            //context.Credentials = creds;

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                SP.List oList = clientContext.Web.Lists.GetByTitle("Persona");

                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem oListItem = oList.AddItem(itemCreateInfo);
                oListItem["Title"]           = persona.Id;
                oListItem["Nombre"]          = persona.Nombre;
                oListItem["Comuna"]          = persona.Comuna;
                oListItem["Direccion"]       = persona.Direccion;
                oListItem["FechaNacimiento"] = persona.FechaNacimiento;
                oListItem["EsHumano"]        = persona.EsHumano;

                oListItem.Update();

                clientContext.ExecuteQuery();
            }
        }
Exemple #9
0
        public async Task <bool> AddItemToList(string listName, SharepointListItem item)
        {
            try
            {
                // Authentication.
                using (var context = _authenticationManager.GetContext(_sharepointUrl))
                {
                    Microsoft.SharePoint.Client.List eventList = context.Web.Lists.GetByTitle(listName);
                    ListItemCreationInformation      itemInfo  = new ListItemCreationInformation();

                    ListItem listItemToAdd = eventList.AddItem(itemInfo);
                    foreach (var field in item)
                    {
                        listItemToAdd[field.Key] = field.Value;
                    }
                    listItemToAdd.Update();
                    await context.ExecuteQueryAsync();

                    return(true);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An unexpected error occurred while adding an item.");
                Console.WriteLine(e.Message);
                return(false);
            }
            // When add item to list, the target list may not exist.
            // Then it should be created and set privilege.
            // Should modify code here and with the help of create list function.
        }
        /// <summary>
        /// Insert a new list item to a specific list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInsertItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SPClient.List announcementsList = ctx.SPContext.Web.Lists.GetByTitle("MyFirstList");

                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem newItem = announcementsList.AddItem(itemCreateInfo);

                newItem["Title"]       = this.txtBoxTitle.Text;
                newItem["Description"] = this.txtBoxDescription.Text;

                newItem.Update();

                ctx.SPContext.ExecuteQuery();

                MessageBox.Show("Item inserted");

                this.txtBoxTitle.Text       = "";
                this.txtBoxDescription.Text = "";
            } catch (Exception ex)
            {
                RaiseException(ex);
            }
        }
        protected void btnAddTask_Click(object sender, EventArgs e)
        {
            string SiteCollectionURL = txtSiteCollection.Text;

            CLOM.ClientContext      context    = new CLOM.ClientContext(SiteCollectionURL);
            CLOM.List               taskList   = context.Web.Lists.GetByTitle("Tasks");
            CLOM.CamlQuery          query      = new CamlQuery();
            CLOM.ListItemCollection myTaskList = taskList.GetItems(query);

            context.Load(myTaskList,
                         itms => itms.ListItemCollectionPosition,
                         itms => itms.Include(
                             itm => itm["Title"],
                             itm => itm["Body"],
                             itm => itm["DueDate"]));

            context.ExecuteQuery();

            ListItemCreationInformation newTask = new ListItemCreationInformation();

            CLOM.ListItem newTaskItem = taskList.AddItem(newTask);

            newTaskItem["Title"]   = txtTitle.Text;
            newTaskItem["Body"]    = txtDesc.Text;
            newTaskItem["DueDate"] = Calendar1.SelectedDate;
            newTaskItem.Update();

            context.ExecuteQuery();

            lblResult.Text = "Added Task " + txtTitle.Text;
        }
Exemple #12
0
        private void btnsave_Click(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(siteurl))
                {
                    throw new Exception("Plase choose site collection in previous tab");
                }

                String title     = txttitle.Text;
                String name      = txtname.Text;
                String allowance = txtallowance.Text;
                String level     = txtlevel.Text;

                if (String.IsNullOrEmpty(title) || String.IsNullOrEmpty(name) || String.IsNullOrEmpty(allowance) || String.IsNullOrEmpty(level))
                {
                    throw new Exception("Please fill all data");
                }

                ClientContext clientContext = new ClientContext(siteurl + "//" + subsite);
                SP.List       oList         = clientContext.Web.Lists.GetByTitle("Resource_Level");

                /** for "edit" function **/
                //ListItem oListItem = oList.GetItemById(title);

                /** Uncomment below code for "add" function **/
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem oListItem = oList.AddItem(itemCreateInfo);

                oListItem["Title"]     = title;
                oListItem["Name"]      = name;
                oListItem["Allowance"] = allowance;
                oListItem["Level"]     = level;

                oListItem.Update();

                clientContext.ExecuteQuery();

                txttitle.Text     = "";
                txtname.Text      = "";
                txtallowance.Text = "";
                txtlevel.Text     = "";

                lblmessage5.Text    = "Data saved successfully";
                lblmessage4.Visible = false;
                lblmessage5.Visible = true;
            }
            catch (Exception ex)
            {
                lblmessage4.Text    = ex.Message;
                lblmessage5.Visible = false;
                lblmessage4.Visible = true;
            }
        }
Exemple #13
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            CLOM.ClientContext context = new CLOM.ClientContext(CLOM.ApplicationContext.Current.Url);

            CLOM.List taskList = context.Web.Lists.GetByTitle("Tasks");

            CLOM.ListItemCreationInformation itemCreateInfo = new CLOM.ListItemCreationInformation();
            CLOM.ListItem newItem = taskList.AddItem(itemCreateInfo);
            newItem["Title"]   = textBox1.Text;
            newItem["DueDate"] = calendar1.SelectedDate.Value.ToShortDateString();
            newItem.Update();

            context.ExecuteQueryAsync(ClientRequestSucceeded, ClientRequestFailed);
        }
        /// <summary>
        /// リストにアイテムを追加します。
        /// </summary>
        /// <param name="this">SharePoint リスト</param>
        /// <param name="leafName">新しいリストアイテムの名前</param>
        /// <param name="isFolder">追加するアイテムがフォルダかどうか</param>
        /// <param name="folderPath">
        /// <para>追加先のフォルダのパス。</para>
        /// <para>絶対パス、又は相対パスを指定します。</para>
        /// <para>指定しない場合はリスト直下にアイテムが追加されます。</para>
        /// </param>
        /// <param name="processItem">追加したアイテムを加工するメソッド</param>
        /// <returns>リストに追加したアイテムを返します。</returns>
        public static void AddItem(this SP.List @this, string leafName, bool isFolder, string folderPath, Action <ListItem> processItem = null)
        {
            var item = @this.AddItem(new ListItemCreationInformation {
                FolderUrl            = folderPath,
                LeafName             = leafName,
                UnderlyingObjectType = isFolder
                                        ? FileSystemObjectType.Folder
                                        : FileSystemObjectType.File,
            });

            processItem?.Invoke(item);

            item.Update();
        }
Exemple #15
0
        private async Task Update_List(string candidateID, string dob)
        {
            try
            {
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem newItem = CandList.AddItem(itemCreateInfo);
                lblStatus.Text = "Uploading Results";
                progressBar1.PerformStep();
                FieldLookupValue lval = await GetLookupValue(ctx, jobName, "Job", "JobFullName", "Text", false);

                newItem["CandidateID"] = CandID;
                newItem["First_name"]  = candidate_name.Split('_')[0];
                newItem["Last_name"]   = candidate_name.Split('_')[1];
                newItem["JobSite"]     = lval;
                newItem["DOB"]         = dob;
                newItem["Job"]         = jobName;
                // double percent = Convert.ToDouble(no_of_passes) / Convert.ToDouble(dt.Rows.Count);
                // string hireStatus = "";
                newItem["Hire_Status"] = hireStatus;
                //if (percent >= 0.7 && percent < 1.0)
                //{
                //    newItem["Hire_Status"] = hireStatus;
                //   // hireStatus = "Conditional Hire";
                //}
                //else
                //{
                //    newItem["Hire_Status"] = "Hired";
                //    hireStatus = "Hired";
                //}
                string        tempFolderurl = docFolder.ServerRelativeUrl;
                FieldUrlValue _url          = new FieldUrlValue();
                _url.Url                  = tempFolderurl.Substring(0, tempFolderurl.LastIndexOf('/'));;
                _url.Description          = "View Tests";
                newItem["FolderUrl"]      = _url;
                newItem["Remaining_Test"] = remaining_test;
                newItem["Category"]       = pos_category;
                //newItem["FolderUrl"] = folder.ServerRelativeUrl;
                newItem.Update();
                ctx.Load(CandList);
                ctx.ExecuteQuery();

                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #16
0
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);

            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
            ListItem oListItem = oList.AddItem(itemCreateInfo);

            oListItem["Title"] = "My New Item!";
            oListItem["Body"]  = "Hello World!";

            oListItem.Update();

            clientContext.ExecuteQuery();
        }
Exemple #17
0
        public void MigrarDatos(List <Persona> ListPersona, HttpContextBase HttpContext)
        {
            LimpiarTabla(HttpContext);
            foreach (Persona persona in ListPersona)
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    //var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

                    //ClientContext clientContext = new ClientContext(siteUrl);
                    SP.List oList = clientContext.Web.Lists.GetByTitle("Persona");

                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem oListItem = oList.AddItem(itemCreateInfo);
                    oListItem["Title"]           = persona.Id;
                    oListItem["Nombre"]          = persona.Nombre;
                    oListItem["Comuna"]          = persona.Comuna;
                    oListItem["Direccion"]       = persona.Direccion;
                    oListItem["FechaNacimiento"] = persona.FechaNacimiento;
                    oListItem["EsHumano"]        = persona.EsHumano;

                    oListItem.Update();

                    clientContext.ExecuteQuery();

                    if (persona.Id % 2 == 0)
                    {
                        oListItem.BreakRoleInheritance(false, false);

                        User spUser = clientContext.Web.CurrentUser;
                        clientContext.Load(spUser, user => user.LoginName);
                        clientContext.ExecuteQuery();

                        //spUser.LoginName
                        User oUser = clientContext.Web.SiteUsers.GetByLoginName("i:0#.f|membership|[email protected]");
                        RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(clientContext);
                        collRoleDefinitionBinding.Add(clientContext.Web.RoleDefinitions.GetByType(RoleType.Reader));
                        oListItem.RoleAssignments.Add(oUser, collRoleDefinitionBinding);
                        clientContext.ExecuteQuery();
                    }
                }
            }
        }
Exemple #18
0
        private static void InsertIntoList(DataTable listTable, string contactListName)
        {
            string siteUrl       = ConfigurationManager.AppSettings["SharePointURL"];
            bool   isBatchUpdate = Convert.ToBoolean(ConfigurationManager.AppSettings["IsBatchUpdate"]);

            using (Microsoft.SharePoint.Client.ClientContext context = ClaimClientContext.GetAuthenticatedContext(siteUrl))
            {
                string strListName = ConfigurationManager.AppSettings["TargetSharePointListName"];
                int    counter     = 0;
                Console.WriteLine(string.Format("\nContent type updation would be performed for url - {0}\n", siteUrl));
                Web site = context.Web;
                context.Load(site);
                context.Load(site.Lists, lists => lists.Include(list => list.Title, // For each list, retrieve Title and Id.
                                                                list => list.Id));
                context.ExecuteQuery();
                Microsoft.SharePoint.Client.List GlossaryList = site.Lists.GetByTitle(strListName);
                for (int iRow = 0; iRow < listTable.Rows.Count; iRow++)
                {
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem oListItem = GlossaryList.AddItem(itemCreateInfo);
                    //the column name below is the absolute name of the column which can be seen in List Settings-->List columns
                    //Modify the below rows as per your target list columns
                    oListItem["Title"] = Convert.ToString(listTable.Rows[iRow][0]); //List Title
                    oListItem["r9dw"]  = Convert.ToString(listTable.Rows[iRow][2]); //Definition
                    oListItem["gpqr"]  = Convert.ToString(listTable.Rows[iRow][3]); //TermCategory
                    counter++;
                    oListItem.Update();
                    if (isBatchUpdate == true)
                    {
                        if ((counter % 10) == 0) //for batch batch by batch updation in multiples of 10
                        {
                            context.ExecuteQuery();
                            counter = 0; //reset the counter
                        }
                    }
                    else
                    {
                        context.ExecuteQuery(); //Either use this if you want to update every item one by one
                    }
                }
            }
        }
Exemple #19
0
 public static SP.ListItem AddItemToList(SP.ClientContext context, SP.List list, Dictionary <string, string> item)
 {
     try
     {
         SP.ListItemCreationInformation itemCreationInfo = new SP.ListItemCreationInformation();
         SP.ListItem newItem = list.AddItem(itemCreationInfo);
         foreach (KeyValuePair <string, string> entry in item)
         {
             newItem[entry.Key] = entry.Value;
         }
         newItem.Update();
         context.Load(newItem);
         context.ExecuteQuery();
         return(newItem);
     }
     catch (Exception e)
     {
         MessageBox.Show($"Error in SharepointMethods.AddItemToList: {e}");
         return(null);
     }
 }
Exemple #20
0
        public void CreateNewEventOnWSS(WorkItem wi)
        {
            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

            oListItem                = oList.AddItem(itemCreateInfo);
            oListItem["Title"]       = wi.DisplayName;
            oListItem["Description"] = wi.Description;
            oListItem["EventDate"]   = wi.ScheduledStartDate;
            oListItem["EndDate"]     = wi.ScheduledEndDate;
            oListItem.Update();

            try
            {
                clientContext.ExecuteQuery();
            }
            catch
            {
                Console.WriteLine("Can't create event on the sharepoint calendar");
                Environment.Exit(3);
            }
        }
        public int AddItem(string ListName, TEntity Item)
        {
            try
            {
                SP.Web  web  = context.Web;
                SP.List list = web.Lists.GetByTitle(ListName);
                SP.ListItemCreationInformation createInfo = new SP.ListItemCreationInformation();
                SP.ListItem item = list.AddItem(createInfo);

                var properties = typeof(TEntity).GetProperties();

                foreach (var property in properties)
                {
                    if (property.PropertyType == typeof(bool?))
                    {
                        item[property.Name] = property.GetValue(Item) != null?property.GetValue(Item) : -1;
                    }
                    else if (property.Name != "ID" && property.Name != "Created" && property.Name != "Author")
                    {
                        item[property.Name] = property.GetValue(Item);
                    }
                }

                item.Update();
                context.Load(item);
                context.ExecuteQuery();

                return(item.Id);
            }
            catch (InvalidCastException ex)
            {
                throw new Exception(ex.Message + ". Data model types are invalid, please verify that models are strongly typed and match the SharePoint list column types.", new InvalidCastException());
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                throw new Exception("Error getting SharePoint list data: " + ex.Message);
            }
        }
Exemple #22
0
        static void SharepointWorker()
        {
            string userName = "******";
            string password = "******";
            string siteUrl  = "https://archimatika.sharepoint.com/sites/TestSiteForCustomization";

            ClientContext clientContext = new ClientContext(siteUrl);

            //Simple auth
            System.Security.SecureString ssPass = new System.Security.SecureString();
            foreach (char c in password)
            {
                ssPass.AppendChar(c);
            }
            ssPass.MakeReadOnly();

            clientContext.Credentials = new SharePointOnlineCredentials(userName, ssPass);
            clientContext.Load(clientContext.Web, web => web.Title);
            clientContext.ExecuteQuery();

            //Get List
            SP.List oList      = clientContext.Web.Lists.GetByTitle("TestList");
            var     listFields = oList.Fields;

            clientContext.Load(listFields, fields => fields.Include(field => field.Title, field => field.InternalName));
            clientContext.ExecuteQuery();

            //Add record to list
            ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
            ListItem oListItem = oList.AddItem(itemCreateInfo);

            oListItem["Title"]             = "PRJ-STG-BLD-R-SBS-001";
            oListItem["GDrive_x002d_GUID"] = "530EC012-0AEC-4C13-B613-152F65416E37";

            oListItem.Update();

            clientContext.ExecuteQuery();
        }
Exemple #23
0
        /// <summary>
        /// CreateFolder - create a folder in a document library using SharePoint Online CSOM
        /// </summary>
        /// <param name="web"></param>
        /// <param name="list"></param>
        /// <param name="folderRelativePath"></param>
        /// <param name="folderName"></param>
        /// <returns></returns>
        private static Microsoft.SharePoint.Client.Folder CreateFolder(Web web, Microsoft.SharePoint.Client.List list, string folderRelativePath, string folderName)
        {
            Microsoft.SharePoint.Client.Folder currentFolder = null;

            try
            {
                list.EnableFolderCreation = true;
                list.Update();
                web.Context.ExecuteQuery();

                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                itemCreateInfo.LeafName             = folderName;

                Microsoft.SharePoint.Client.ListItem newFolder = list.AddItem(itemCreateInfo);
                newFolder["Title"] = folderName;
                newFolder.Update();
                web.Context.ExecuteQuery();

                Microsoft.SharePoint.Client.Folder rootFolder = list.RootFolder;
                web.Context.Load(rootFolder);
                web.Context.ExecuteQuery();

                FolderCollection folders = rootFolder.Folders;
                web.Context.Load(folders);
                web.Context.ExecuteQuery();

                currentFolder = list.RootFolder.Folders[list.RootFolder.Folders.Count - 1];
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error creating new folder named {0}", folderName);
                Console.WriteLine("Exception: {0}", ex.Message);
                return(null);
            }

            return(currentFolder);
        }
Exemple #24
0
        private void Edit(Employee emp)
        {
            if (oList != null)
            {
                string lang = GetLanguage(emp.Languages);
                // Edit
                if (emp.Id != 0)
                {
                    // Assume there is a list item with ID=1.
                    ListItem listItem = oList.GetItemById(emp.Id);

                    // Write a new value to the Body field of the Announcement item.
                    listItem["EmailAdd"]             = emp.Email;
                    listItem["ShortDesc"]            = emp.ShortDescription;
                    listItem["FirstName"]            = emp.FirstName;
                    listItem["Title"]                = emp.Title;
                    listItem["ProgrammingLanguages"] = lang;
                    listItem.Update();

                    context.ExecuteQuery();
                }
                // Add new item
                else
                {
                    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                    ListItem newItem = oList.AddItem(itemCreateInfo);
                    newItem["EmailAdd"]             = emp.Email;
                    newItem["ShortDesc"]            = emp.ShortDescription;
                    newItem["FirstName"]            = emp.FirstName;
                    newItem["Title"]                = emp.Title;
                    newItem["ProgrammingLanguages"] = lang;
                    newItem.Update();

                    context.ExecuteQuery();
                }
            }
        }
Exemple #25
0
        public void sentdatatoSPLIst()
        {
            int sem  = 0;
            int Year = LibraryMOD.SeperateTerm(LibraryMOD.GetCurrentTerm(), out sem);

            int    iYear     = Year;
            int    iSem      = sem;
            string sSemester = LibraryMOD.GetSemesterString(iSem);

            string login          = "******"; //give your username here
            string password       = "******";                 //give your password
            var    securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            string        siteUrl       = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices";
            ClientContext clientContext = new ClientContext(siteUrl);

            Microsoft.SharePoint.Client.List myList   = clientContext.Web.Lists.GetByTitle("Students_Requests");
            ListItemCreationInformation      itemInfo = new ListItemCreationInformation();

            Microsoft.SharePoint.Client.ListItem myItem = myList.AddItem(itemInfo);
            string refno = Create16DigitString();

            myItem["Title"] = refno;
            //myItem["RequestID"] = refno;
            myItem["Year"]        = iYear;
            myItem["Semester"]    = iSem;
            myItem["Request"]     = "<b>Service ID:</b> " + lbl_ServiceID.Text + "<br/> <b>Service Name:</b> " + lbl_ServiceNameEn.Text + " (" + lbl_ServiceNameAr.Text + " )";
            myItem["RequestNote"] = txt_Remarks.Text.Trim();
            myItem["ServiceID"]   = lbl_ServiceID.Text;
            myItem["Fees"]        = hdf_Price.Value;
            //myItem["Requester"] = clientContext.Web.EnsureUser(hdf_StudentEmail.Value);
            myItem["Requester"]     = clientContext.Web.EnsureUser("*****@*****.**");
            myItem["StudentID"]     = lbl_StudentID.Text;
            myItem["StudentName"]   = lbl_StudentName.Text;
            myItem["Contact"]       = lbl_StudentContact.Text;
            myItem["Finance"]       = clientContext.Web.EnsureUser("*****@*****.**");
            myItem["FinanceAction"] = "Initiate";
            myItem["FinanceNote"]   = "";
            myItem["Host"]          = clientContext.Web.EnsureUser("*****@*****.**");
            myItem["HostAction"]    = "Initiate";
            myItem["HostNote"]      = "";
            //myItem["Provider"] = "";
            myItem["ProviderAction"] = "Initiate";
            myItem["ProviderNote"]   = "";
            myItem["Status"]         = "Finance Approval Needed";
            //myItem["Modified"] = DateTime.Now;
            //myItem["Created"] = DateTime.Now;
            //myItem["Created By"] = hdf_StudentEmail.Value;
            //myItem["Modified By"] = hdf_StudentEmail.Value;
            try
            {
                myItem.Update();

                //if (flp_Upload.HasFile)
                //{
                //    var attachment = new AttachmentCreationInformation();

                //    flp_Upload.SaveAs(Server.MapPath("~/Upload/" + flp_Upload.FileName));
                //    string FileUrl = Server.MapPath("~/Upload/" + flp_Upload.FileName);

                //    string filePath = FileUrl;
                //    attachment.FileName = Path.GetFileName(filePath);
                //    attachment.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filePath));
                //    Attachment att = myItem.AttachmentFiles.Add(attachment);
                //}

                var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
                clientContext.Credentials = onlineCredentials;
                clientContext.ExecuteQuery();

                //string FileUrls = Server.MapPath("~/Upload/" + flp_Upload.FileName);
                //System.IO.File.Delete(FileUrls);

                lbl_Msg.Text         = "Request (ID# " + refno + ") Generated Successfully";
                lbl_Msg.Visible      = true;
                div_msg.Visible      = true;
                lnk_Generate.Enabled = false;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            //Console.ReadLine();
        }
Exemple #26
0
        public void addAllData(string listTitle)
        {
            Web web = mClientContext.Web;

            SP.List projList = mClientContext.Web.Lists.GetByTitle(listTitle);
            Dictionary <int, Milestone> milestoneDict = mProg.getMilestoneObjMap();
            bool isOrdered = false;

            Console.WriteLine("the error code is: " + this.mEmailError.getErrorCode());
            if (this.mIsNewList == false)
            {
                readData(listTitle);
                isOrdered = milestonesAreOrdered(milestoneDict, false);
                inputMilestoneAddCommands(milestoneDict);
            }
            else
            {
                isOrdered = milestonesAreOrdered(milestoneDict, true);
                inputMilestoneAddCommands(milestoneDict);
            }
            if ((this.mEmailError.getErrorCode() == 0 || this.mEmailError.getErrorCode() == -1) && isOrdered == true)
            {
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem oListItem = projList.AddItem(itemCreateInfo);
                Console.WriteLine("milestone size is: " + mProg.getMMilestoneSize());
                oListItem["Estimated_x0020_Start_x0020_Time"] = mProg.getMEstStartTime();
                oListItem["Estimated_x0020_Start_x0020_Date"] = mProg.getMEstStartDate();
                oListItem["Estimated_x0020_End_x0020_Time"]   = mProg.getMEstEndTime();
                oListItem["Estimated_x0020_End_x0020_Date"]   = mProg.getMEstEndDate();
                oListItem["Actual_x0020_Start_x0020_Time"]    = mProg.getMActualStartTime();
                oListItem["Actual_x0020_Start_x0020_Date"]    = mProg.getMActualStartDate();
                oListItem["Time_x0020_Spent"]                 = mProg.getMTimeSpent();
                oListItem["Resources"]                        = mProg.getMResources();
                oListItem["Current_x0020_Status"]             = mProg.getMCurrentStatus();
                oListItem["Current_x0020_Status_x0020_Reaso"] = mProg.getMStatusReason();
                List <int> addCommand    = new List <int>();
                List <int> updateCommand = new List <int>();
                List <int> removeCommand = new List <int>();
                //if(this.mIsNewList == true)
                //{
                //    foreach (var pair in mProg.getMilestoneObjMap().OrderBy(i => i.Key))
                //    {
                //        Milestone milestone = pair.Value;
                //        Console.WriteLine("the milestone command is: " + milestone.getCommand().Trim());
                //        if (milestone.getCommand().Trim() == "Add")
                //        {
                //            milestoneAddHandler(projList, oListItem, milestone);
                //        }
                //    }
                //}
                if (this.milestonesWithAddCommands.Count > 0)
                {
                    for (int i = 0; i < this.milestonesWithAddCommands.Count; i++)
                    {
                        milestoneDict.TryGetValue(this.milestonesWithAddCommands[i], out Milestone milestone);
                        if (milestone != null)
                        {
                            milestoneAddHandler(projList, oListItem, milestone);
                            //if (milestone.getCommand().Trim() == "Update")
                            //{
                            //    updateCommand.Add(milestone.getNumber());
                            //}
                            //if (milestone.getCommand().Trim() == "Remove")
                            //{
                            //    removeCommand.Add(milestone.getNumber());
                            //}
                        }
                    }
                }

                //foreach (var pair in mProg.getMilestoneObjMap().OrderBy(i => i.Key))
                //{
                //    Milestone milestone = pair.Value;
                //    Console.WriteLine("the milestone command is: " + milestone.getCommand().Trim());
                //    if (milestone.getCommand().Trim() == "Add")
                //    {
                //        addCommand.Add(milestone.getNumber());
                //        milestoneCommandHandler(projList, oListItem, milestone);
                //    }
                //    else if (milestone.getCommand().Trim() == "Update")
                //    {
                //        updateCommand.Add(milestone.getNumber());
                //    }
                //    else if (milestone.getCommand().Trim() == "Remove")
                //    {
                //        removeCommand.Add(milestone.getNumber());
                //    }
                //}
                //updateMilestones(projList, updateCommand, removeCommand, addCommand);
                //Console.WriteLine("the milestone number is: " + mProg.getMMilestoneNum(pair.Key));
                //}
                //}else if(milestone.getCommand().Trim() == "Update" || milestone.getCommand().Trim() == "Remove")
                //{s
                //    milestoneCommandHandler(projList, oListItem, milestone);
                //}
                //oListItem.Update();
                //mClientContext.ExecuteQuery();



                //oListItem.Update();
                //SP.CamlQuery myQuery = new SP.CamlQuery();
                //myQuery.ViewXml = " < Where > < Eq > < FieldRef Name = 'Milestone_x0020_Number' /> <Value Type = 'Text'> 2 </Value> </ Eq > </ Where ></ View >";
                //SP.ListItemCollection collectItems = projList.GetItems(myQuery);
                //mClientContext.Load(collectItems);

                Console.WriteLine("MUST UPDATE");
                this.mInitialMilestoneRowCount = 0;
                oListItem.Update();

                mClientContext.ExecuteQuery();
            }
            else
            {
                this.mEmailError.setErrorCheck(true);
                if (isOrdered == false)
                {
                    string mailboxAddress = mProg.getMailItem().mMailboxAddress;
                    mEmailError.sendMilestoneTooLargeErrorEmail(mailboxAddress);
                    this.mEmailError.setErrorCode(3);
                }
            }
        }
Exemple #27
0
        private async Task upload_new_Candidates(DataRow row, Microsoft.SharePoint.Client.ClientContext context, Microsoft.SharePoint.Client.List doclist, Microsoft.SharePoint.Client.List list)
        {
            try
            {
                Microsoft.SharePoint.Client.ListItemCollection listitems = list.GetItems(Microsoft.SharePoint.Client.CamlQuery.CreateAllItemsQuery());
                context.Load(listitems);
                context.ExecuteQuery();
                string candID;
                if (listitems.Count > 0)
                {
                    candID = Convert.ToString(get_nextCandidateID(listitems) + 1);
                }
                else
                {
                    candID = "1000";
                }
                // row["Current_Status"] = "Creating Folders";
                Folder folder = CreateFolderInternal(context.Web, doclist.RootFolder, candID + "_" + row["First_Name"] + "_" + row["Last_Name"] + "/" + row["Job"]);
                //row["Current_Status"] = "Uploading Files";
                string[] files = Directory.GetFiles(Convert.ToString(row["Folder_path"]));
                await Task.Delay(1000);

                foreach (string filename in files)
                {
                    using (var fs = new FileStream(filename, FileMode.Open))
                    {
                        var fi = new FileInfo(filename);
                        //var list = clientContext.Web.Lists.GetByTitle(listTitle);
                        Folder targetFolder = context.Web.GetFolderByServerRelativeUrl(folder.ServerRelativeUrl);
                        context.Load(targetFolder);
                        context.ExecuteQuery();
                        var fileUrl = String.Format("{0}/{1}", targetFolder.ServerRelativeUrl, fi.Name);

                        Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
                    }
                }

                //  row["Current_Status"] = "Adding Item";
                ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
                ListItem         newItem = list.AddItem(itemCreateInfo);
                FieldLookupValue lval    = await GetLookupValue(ctx, Convert.ToString(row["Job"]), "Job", "JobFullName", "Text", false);

                newItem["CandidateID"] = candID;
                newItem["First_name"]  = Convert.ToString(row["First_Name"]);
                newItem["Last_name"]   = Convert.ToString(row["Last_Name"]);
                newItem["JobSite"]     = lval;
                newItem["Job"]         = Convert.ToString(row["Job"]);
                newItem["DOB"]         = Convert.ToString(row["DOB"]);
                // double percent = Convert.ToDouble(no_of_passes) / Convert.ToDouble(dt.Rows.Count);
                // string hireStatus = "";
                newItem["Hire_Status"] = Convert.ToString(row["Pass_Status"]);
                //if (percent >= 0.7 && percent < 1.0)
                //{
                //    newItem["Hire_Status"] = hireStatus;
                //   // hireStatus = "Conditional Hire";
                //}
                //else
                //{
                //    newItem["Hire_Status"] = "Hired";
                //    hireStatus = "Hired";
                //}
                string        tempFolderurl = folder.ServerRelativeUrl;
                FieldUrlValue _url          = new FieldUrlValue();
                _url.Url                  = tempFolderurl.Substring(0, tempFolderurl.LastIndexOf('/'));;
                _url.Description          = "View Tests";
                newItem["FolderUrl"]      = _url;
                newItem["Remaining_Test"] = Convert.ToString(row["Remaining_Test"]);
                newItem["Category"]       = Convert.ToString(row["Position"]);;
                //newItem["FolderUrl"] = folder.ServerRelativeUrl;
                newItem.Update();
                context.Load(list);
                context.ExecuteQuery();
                await Task.Delay(1000);

                // row["Current_Status"] = "Uploaded";

                XmlNode deleteNode = read_local_data_store(xmlDoc, row);
                if (deleteNode != null)
                {
                    deleteNode.ParentNode.RemoveChild(deleteNode);
                }

                await Task.Delay(1000);

                xmlDoc.Save(get_local_data_path() + cmbxJobList.SelectedValue + "\\" + "History.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public static bool EmailData(List <ITAssets> updationList, string siteUrl, string listName)
        {
            bool retValue = false;

            try
            {
                using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl))
                {
                    //List<Mailing> varx = new List<Mailing>();

                    MSC.List list = context.Web.Lists.GetByTitle(listName);
                    for (var i = 0; i < updationList.Count; i++)
                    {
                        var updateList = updationList.Skip(i).Take(1).ToList();
                        if (updateList != null && updateList.Count > 0)
                        {
                            foreach (var updateItem in updateList)
                            {
                                MSC.ListItem listItem = null;

                                MSC.ListItemCreationInformation itemCreateInfo = new MSC.ListItemCreationInformation();
                                listItem = list.AddItem(itemCreateInfo);

                                var obj = new Object();
                                //Mailing data = new Mailing();

                                //var _From = "";
                                var _To = "";
                                //var _Cc = "";
                                var _Body    = "";
                                var _Subject = "";
                                if (updateItem.StatusId == "0")
                                {
                                    _To = updateItem.FunctionalHead;
                                }
                                else
                                {
                                    _To = updateItem.AssignedApprover;
                                }
                                _Subject = "Gentle Reminder"; // + updateItem.ExpVoucherNo + " Travel Voucher Approval is Pending
                                _Body   += "Dear User, <br><br>This is to inform you that below request is pending for your Approval.";
                                _Body   += "<br><b>Workflow Name :</b> IT Asset Requisition ";
                                _Body   += "<br><b>Request No :</b>  " + updateItem.RequisitionNo;
                                _Body   += "<br><b>Date of Requisition :</b>  " + updateItem.StartOn;
                                _Body   += "<br><b>Requested By  : </b> " + updateItem.EmployeeName;
                                _Body   += "<br><b>Location :</b> " + updateItem.Location;
                                _Body   += "<br><b>Department :</b> " + updateItem.Department;
                                _Body   += "<br><b>Designation :</b> " + updateItem.Designation;
                                _Body   += "<br><b>Buisness :</b> " + updateItem.Business;
                                _Body   += "<br><b>Reporting to  :</b> " + updateItem.ReportingTo;
                                if (updateItem.Asset == "Desktop")
                                {
                                    _Body += "<br><b>IT Asset Request for  :</b> " + updateItem.Asset;
                                }
                                else
                                {
                                    _Body += "<br><b>Based on Work Level  :</b> " + updateItem.Asset;
                                }

                                _Body += "<br><b>New Joinee Employee :</b> " + updateItem.NewJoineeEmpName;
                                _Body += "<br><b>New Employee designation :</b> " + updateItem.NewEmployeeDesignation;
                                _Body += "<br><b>Replacement Of :</b> " + updateItem.ReplacementEmployeeName;
                                if (updateItem.StatusId == "0")
                                {
                                    _Body += "<br><b>Status :</b> " + updateItem.Status;
                                }
                                else if (updateItem.StatusId == "1")
                                {
                                    _Body += "<br><b>Status :</b> " + updateItem.Status;
                                }
                                else if (updateItem.StatusId == "4")
                                {
                                    _Body += "<br><b>Status :</b> " + updateItem.Status;
                                }
                                else if (updateItem.StatusId == "5")
                                {
                                    _Body += "<br><b>Status :</b> " + updateItem.Status;
                                }
                                else if (updateItem.StatusId == "6")
                                {
                                    _Body += "<br><b>Status :</b> " + updateItem.Status;
                                }
                                else if (updateItem.StatusId == "7")
                                {
                                    _Body += "<br><b>Status :</b> " + updateItem.Status;
                                }
                                _Body += "<br><h3>Kindly provide your approval</h3>";
                                _Body += "<br><h3>For Approval Please Click in the below link</h3>";
                                if (updateItem.StatusId == "0")
                                {
                                    _Body += "<br><a href=\"https://aparindltd.sharepoint.com/ITAssetRequisition/SitePages/PendingForMe.aspx?StatusId=" + updateItem.StatusId + "&RequisitionNo=\">View Link</a>";
                                }
                                else if (updateItem.StatusId == "1")
                                {
                                    _Body += "<br><a href=\"https://aparindltd.sharepoint.com/ITAssetRequisition/SitePages/PendingForMe.aspx?StatusId=" + updateItem.StatusId + "&RequisitionNo=\">View Link</a>";
                                }
                                else if (updateItem.StatusId == "4")
                                {
                                    _Body += "<br><a href=\"https://aparindltd.sharepoint.com/ITAssetRequisition/SitePages/PendingForMe.aspx?StatusId=" + updateItem.StatusId + "&RequisitionNo=\">View Link</a>";
                                }
                                else if (updateItem.StatusId == "5")
                                {
                                    _Body += "<br><a href=\"https://aparindltd.sharepoint.com/ITAssetRequisition/SitePages/PendingForMe.aspx?StatusId=" + updateItem.StatusId + "&RequisitionNo=\">View Link</a>";
                                }
                                else if (updateItem.StatusId == "6")
                                {
                                    _Body += "<br><a href=\"https://aparindltd.sharepoint.com/ITAssetRequisition/SitePages/PendingForMe.aspx?StatusId=" + updateItem.StatusId + "&RequisitionNo=\">View Link</a>";
                                }
                                else if (updateItem.StatusId == "7")
                                {
                                    _Body += "<br><a href=\"https://aparindltd.sharepoint.com/ITAssetRequisition/SitePages/PendingForMe.aspx?StatusId=" + updateItem.StatusId + "&RequisitionNo=\">View Link</a>";
                                }
                                //data.MailTo = _From;
                                //data.MailTo = _To;
                                //data.MailCC = _Cc;
                                //data.MailSubject = _Subject;
                                //data.MailBody = _Body;
                                //varx.Add(data);
                                listItem["ToUser"]      = _To;
                                listItem["MailSubject"] = _Subject;
                                listItem["MailBody"]    = _Body;
                                listItem.Update();
                            }
                            try
                            {
                                context.ExecuteQuery();
                                retValue = true;
                            }
                            catch (Exception ex)
                            {
                                CustomSharePointUtility.WriteLog(string.Format("Error in  InsertUpdate_EmployeeMaster ( context.ExecuteQuery();): Error ({0}) ", ex.Message));
                                return(false);
                                //continue;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CustomSharePointUtility.WriteLog(string.Format("Error in  InsertUpdate_EmployeeMaster: Error ({0}) ", ex.Message));
            }
            return(retValue);
        }
Exemple #29
0
        public static bool EmailData(PurchaseOrder updationList, string FunctionalHeadEmail, string PurchaseHead, string PlantHead, string MD, string siteUrl, string listName)
        {
            bool retValue = false;

            try
            {
                using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl))
                {
                    //List<Mailing> varx = new List<Mailing>();

                    MSC.List list = context.Web.Lists.GetByTitle(listName);
                    //for (var i = 0; i < updationList.Count; i++)
                    //{
                    //var updateList = updationList.Skip(i).Take(1).ToList();
                    //if (updateList != null && updateList.Count > 0)
                    //{
                    //    foreach (var updateItem in updateList)
                    //    {
                    MSC.ListItem listItem = null;

                    MSC.ListItemCreationInformation itemCreateInfo = new MSC.ListItemCreationInformation();
                    listItem = list.AddItem(itemCreateInfo);

                    var obj = new Object();
                    //Mailing data = new Mailing();

                    //var _From = "";
                    var _To = "";
                    //var _Cc = "";
                    var _Body    = "";
                    var _Subject = "";
                    if (updationList.ApprovalStatus == "Submitted" && updationList.LocationType == "Office")
                    {
                        _To = FunctionalHeadEmail;
                    }
                    else if (updationList.ApprovalStatus == "Approved By Functional Head" && updationList.LocationType == "Office")
                    {
                        _To = MD;
                    }
                    else if (updationList.ApprovalStatus == "Submitted" && updationList.LocationType == "Plant")
                    {
                        _To = PurchaseHead;
                    }
                    else if (updationList.ApprovalStatus == "Approved By Purchase Head" && updationList.LocationType == "Plant")
                    {
                        _To = PlantHead;
                    }
                    else if (updationList.ApprovalStatus == "Approved By Plant Head" && Convert.ToInt32(updationList.POCost) > 50000 && updationList.LocationType == "Plant")
                    {
                        _To = MD;
                    }

                    _Subject = "Gentle Reminder";
                    _Body   += "Dear User, <br><br>This is to inform you that below request is pending for your Approval.";
                    _Body   += "<br><b>Workflow Name :</b> Purchase Order ";
                    _Body   += "<br><b>Voucher No :</b>  " + updationList.POReferenceNumber;
                    _Body   += "<br><b>Date of Creation :</b>  " + updationList.Created;
                    _Body   += "<br><b>Employee : </b> " + updationList.Author;

                    _Body += "<br><b>Department :</b> " + updationList.DepartmentName;
                    _Body += "<br><b>Location :</b> " + updationList.LocationName;
                    _Body += "<br><b>PO No : </b> " + updationList.PONumber;
                    _Body += "<br><b> PO Amount : </b> " + updationList.POCost;
                    _Body += "<br><b> Material Details : </b> " + updationList.MaterialDetails;

                    if (updationList.ApprovalStatus == "Submitted" && updationList.LocationType == "Office")
                    {
                        _Body += "<br><b>Status :</b> Pending With Functional Head";
                    }
                    else if (updationList.ApprovalStatus == "Approved By Functional Head" && updationList.LocationType == "Office")
                    {
                        _Body += "<br><b>Status :</b> Pending With MD";
                    }
                    else if (updationList.ApprovalStatus == "Submitted" && updationList.LocationType == "Plant")
                    {
                        _Body += "<br><b>Status :</b> Pending With Purchase Head";
                    }
                    else if (updationList.ApprovalStatus == "Approved By Purchase Head" && updationList.LocationType == "Plant")
                    {
                        _Body += "<br><b>Status :</b> Pending With Plant Head";
                    }
                    else if (updationList.ApprovalStatus == "Approved By Plant Head" && Convert.ToInt32(updationList.POCost) > 50000 && updationList.LocationType == "Plant")
                    {
                        _Body += "<br><b>Status :</b> Pending With MD";
                    }

                    _Body += "<br><h3>Kindly provide your approval</h3>";
                    _Body += "<br><h3>For Approval Please Click in the below link</h3>";
                    if (updationList.ApprovalStatus == "Submitted" && updationList.LocationType == "Office")
                    {
                        //         _Body += "<br><a href=\"https://aparindltd.sharepoint.com/PurchaseOrder/SitePages/PendingWithFunctionalHead.aspx\">View Link</a>";
                    }
                    else if (updationList.ApprovalStatus == "Approved By Functional Head" && updationList.LocationType == "Office")
                    {
                        //       _Body += "<br><a href=\"https://aparindltd.sharepoint.com/PurchaseOrder/SitePages/PendingWithMD.aspx\">View Link</a>";
                    }
                    else if (updationList.ApprovalStatus == "Submitted" && updationList.LocationType == "Plant")
                    {
                        //       _Body += "<br><a href=\"https://aparindltd.sharepoint.com/PurchaseOrder/SitePages/PendingWithPurchaseHead.aspx\">View Link</a>";
                    }
                    else if (updationList.ApprovalStatus == "Approved By Purchase Head" && updationList.LocationType == "Plant")
                    {
                        //     _Body += "<br><a href=\"https://aparindltd.sharepoint.com/PurchaseOrder/SitePages/PendingWithPlantHead.aspx\">View Link</a>";
                    }
                    else if (updationList.ApprovalStatus == "Approved By Plant Head" && updationList.LocationType == "Plant")
                    {
                        //      _Body += "<br><a href=\"https://aparindltd.sharepoint.com/PurchaseOrder/SitePages/PendingWithManagingDirector.aspx\">View Link</a>";
                    }

                    //data.MailTo = _From;
                    //data.MailTo = _To;
                    //data.MailCC = _Cc;
                    //data.MailSubject = _Subject;
                    //data.MailBody = _Body;
                    //varx.Add(data);
                    listItem["ToUser"]      = _To;
                    listItem["SubjectDesc"] = _Subject;
                    listItem["BodyDesc"]    = _Body;
                    if (_To != "")
                    {
                        listItem.Update();
                    }
                    try
                    {
                        context.ExecuteQuery();
                        retValue = true;
                    }
                    catch (Exception ex)
                    {
                        CustomSharePointUtility.WriteLog(string.Format("Error in  InsertUpdate_EmployeeMaster ( context.ExecuteQuery();): Error ({0}) ", ex.Message));
                        return(false);
                        //continue;
                    }
                }

                //        }
                //    }
                //}

                //}
            }

            catch (Exception ex)
            {
                CustomSharePointUtility.WriteLog(string.Format("Error in  InsertUpdate_EmployeeMaster: Error ({0}) ", ex.Message));
            }
            return(retValue);
        }
Exemple #30
0
        public static bool EmailDataPlant(PurchaseOrder updationList, string siteUrl, string listName)
        {
            bool retValue = false;

            try
            {
                using (MSC.ClientContext context = CustomSharePointUtility.GetContext(siteUrl))
                {
                    //List<Mailing> varx = new List<Mailing>();

                    MSC.List list = context.Web.Lists.GetByTitle(listName);

                    MSC.ListItem listItem = null;

                    MSC.ListItemCreationInformation itemCreateInfo = new MSC.ListItemCreationInformation();
                    listItem = list.AddItem(itemCreateInfo);

                    var obj = new Object();

                    var _To      = "";
                    var _Body    = "";
                    var _Subject = "";

                    _To = updationList.CurrentApprover;


                    _Subject = "Gentle Reminder";
                    _Body   += "Dear User, <br><br>This is to inform you that below request is pending for your Approval.";
                    _Body   += "<br><b>Workflow Name :</b> Purchase Order ";
                    _Body   += "<br><b>Voucher No :</b>  " + updationList.POReferenceNumber;
                    _Body   += "<br><b>Date of Creation :</b>  " + updationList.Created;
                    _Body   += "<br><b>Employee : </b> " + updationList.Author;

                    _Body += "<br><b>Department :</b> " + updationList.DepartmentName;
                    _Body += "<br><b>Location :</b> " + updationList.LocationName;
                    _Body += "<br><b>PO No : </b> " + updationList.PONumber;
                    _Body += "<br><b> PO Amount : </b> " + updationList.POCost;
                    _Body += "<br><b> Material Details : </b> " + updationList.MaterialDetails;

                    if (updationList.NewStatus == "1")
                    {
                        _Body += "<br><b>Status :</b> Pending With Purchase Head";
                    }
                    else if (updationList.NewStatus == "2")
                    {
                        _Body += "<br><b>Status :</b> Pending With Plant Head";
                    }


                    _Body += "<br><h3>Kindly provide your approval</h3>";
                    _Body += "<br><h3>For Approval Please Click in the below link</h3>";
                    if (updationList.NewStatus == "1")
                    {
                        ///       _Body += "<br><a href=\"https://aparindltd.sharepoint.com/PurchaseOrder/SitePages/PendingWithApprover.aspx\">View Link</a>";
                    }
                    else if (updationList.NewStatus == "2")
                    {
                        ///      _Body += "<br><a href=\"https://aparindltd.sharepoint.com/PurchaseOrder/SitePages/PendingWithManagingDirector.aspx\">View Link</a>";
                    }

                    listItem["ToUser"]      = _To;
                    listItem["SubjectDesc"] = _Subject;
                    listItem["BodyDesc"]    = _Body;

                    if (_To != "")
                    {
                        listItem.Update();
                    }
                    try
                    {
                        context.ExecuteQuery();
                        retValue = true;
                    }
                    catch (Exception ex)
                    {
                        CustomSharePointUtility.WriteLog(string.Format("Error in  InsertUpdate_EmployeeMaster ( context.ExecuteQuery();): Error ({0}) ", ex.Message));
                        return(false);
                        //continue;
                    }
                }
            }

            catch (Exception ex)
            {
                CustomSharePointUtility.WriteLog(string.Format("Error in  InsertUpdate_EmployeeMaster: Error ({0}) ", ex.Message));
            }
            return(retValue);
        }