Programmatically create content database in C# (SP 2013)

The goal is to have a web user interface with the option to create new site collections with new Content Database.

With the admin user I can manually in the CA create new Content Databases. I can also create a new site collection in this content database.

The idea was to create an event receiver (C#). If the user adds data to a table, the mentioned actions are to be executed.

Experiments: a) Console application – works!

using (SPSite site = new SPSite("http://sp2013")) {   using (SPWeb spWeb = site.OpenWeb()) {       SPWebApplication elevatedWebApp = spWeb.Site.WebApplication;         elevatedWebApp.ContentDatabases.Add("sp2013", "WSS_Content_80_" + DateTime.Now.ToString("yyyymmddhhMMss"), null, null, 10, 15, 0);     } } 

b) Event Receiver – Only create site collections works, creation of content databases does not work! Error: Access Denied.

c) Web Service – Does not work! Error: Access Denied.

So, why do I get the error Access Denied when I can create site collections, but only content databases creation not go?

Finally I executed PS Script – but this also doesn´t work.

# AUTHOR: Paul Kotlyar # CONTACT: unclepaul84@gmail.com # DESCRIPTION: sets an option on content web service that allows updating of SP Administration objects such as SPJobDefinition from content web applications function Set-RemoteAdministratorAccessDenied-False() {     # load sharepoint api libs     [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $  null     [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration") > $  null    # get content web service  $  contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService   # turn off remote administration security  $  contentService.RemoteAdministratorAccessDenied = $  false   # update the web service  $  contentService.Update() } 

Maybe somebody knows a solution?

Programmatically change a Date field

I have a form/web part where the user can edit columns. It works, but when the user needs to change value in a date column, it doesn’t work.

First I have the input form:

 <Calendar               value={this.props.item.Date}               strings={DayPickerStrings}               onSelectDate={(value: Date) => this.setDate(value)}               isMonthPickerVisible={false}         /> 

It values sends back to a function that saves it to a state with “Date” type:

public setDate = e => this.setState({ changeDate: e}); 

I then try to pass it to the list with the following function:

 if (this.state.changeDate) {        eventList.items   //my list         .getById(this.props.item.ID)     .get()     .then(async item => {       eventList.items         .getById(this.props.item.ID)          .validateUpdateListItem([           {             FieldName: "EventDate",             FieldValue: JSON.stringify(this.state.changeDate)           }         ])          .then(result => {           this.props.handleToUpdate();         });     }); } 

It doesn’t work and the column doesn’t update with the new values. Why doesnt the column update with the value from the state?

Programmatically create and Add Owners and Members to O365 Group, no emails are sent

I’m using the code found in OfficeDevPnP.Core to create a new UnifiedGroup. UnifiedGroupsUtitlity.CreateUnifiedGroup. My code is below.

UnifiedGroupsUtility.CreateUnifiedGroup("CSOM Site Creation",                                                             "My Site Created in Code,                                                             CSOM,                                                             accessToken,                                                             groupLogo: null,                                                             owners: owners.ToArray(),                                                             members: members.ToArray(),                                                             isPrivate: true,                                                             createTeam: false); 

When I’m using this code, none of the Owners or members get’s an email saying they have joined the group, like they do if I add them manually to a group.

Do I have to write that part of the code to send the emails, or is there another method I can use that’s already out there to send the same template that Microsoft sends?

There are two emails sent (if MS Teams included), when adding a person manually. One to say the person is added to the group from: The site on behalf of me. One to say the person is added to the MS Teams. From: noreply@email.teams.microsoft.com

It these emails I wish to replicate when adding a user to Group/Team.

Add properties to modern site programmatically

I want to add some metadata to my modern Team Site.

I can achieve this by simply adding columns to the Site Pages library in the site contents.

Now I want to do the same thing programmatically using CSOM.

I use the following code for that purpose:

var pages = siteContext.Web.Lists.GetByTitle("Site Pages"); var fieldCreationInformation = new OfficeDevPnP.Core.Entities.FieldCreationInformation(fieldType) {     DisplayName = fieldName,     InternalName = fieldName.Replace(" ", ""),     AddToDefaultView = true,     Required = false,     Id = Guid.NewGuid() }; pages.CreateField(fieldCreationInformation); 

This works – the fields are getting added to the pages library, however they don’t appear as the properties when I’m editing the page, unlike the columns added in the GUI.

Why? How can I add columns programmatically and see them as page properties?

Programmatically trigger flow and send properties

I want to manually trigger an external flow from my SPFX project, and at the same time send values to the flow.

In flow, I have my request body:

{ "$  schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": {     "emailaddress": {         "type": "string"     },     "id": {         "type": "number"     }, }, "required": [     "emailaddress",     "id" ]  } 

I have the unique URL/Path to my flow. But how do I connect to flow (via this path, or some other possible way) and at the same time send data to it? I’m using javascript/react.

ssign permission of the current user to a list item programmatically

I am making an event web part which is connected to a list of items. When a user attends an event, a json object will be parsed to a txt document that is attached to that particular list item /event. with the user details. However, when an user does not have edit permission, this will not work. In this case I want to give the user edit permissions. Im using sharepoint online.

I was thinking to use REST API to change the users permissions for that particular list item, but from what I could gather it, seems it only works for groups permission etc and not for the current user. Have I missed something, or do I need to user another kind of method?

New Column added programmatically to Content Type in Hub not propagating to the List in SharePoint 2013

I have a SharePoint 2013 Multi Tenant environment. I have a Content Type Hub, a Root Site and a Document Center in addition to a Tenant Admin site in every tenant. I have a Custom Visual Studio solution for adding Content Types and Site Columns to my Content Type Hub. The Content Types and Site Columns are created declaratively in Visua Studio. These Content Types are pushed to the Root Site (and all the other subscribing sites within the tenant as well). The Root Site has the required lists, which use these Content Types. These lists have data now.

Now I have to make changes to the Content Types in the Hub by changing an existing column (say changing a column type from Single Line of Text to Multiline). I went back to my solution in Visual Studio and made the change to the Site Column declaratively. Now, I retracted and redeployed the solution and on feature activation, I published the Content Type, the subscribing site got this change and so did the list. Since it was a change from Single Line of Text to Multiline, there was also no data loss.

I also have to add a column now to the content type. After I did this in my Visual Studio project, I retracted and redeployed it and published the content type through the feature activation. I could see that the Root Site also got this change in it’s Site Content Types list and I could see the newly added column. But, I was quite amazed to observe that the existing Content Type in the list is not showing the newly added column. But strangely, this works if I am adding a column to the content type through UI and then I am publishing it. I am not sure, what am I doing wrong here. Is there a way to achieve it, through code? I am sure there will be, since it is happening through UI. Please help.

PS: The site is live and hence I can’t take any risk.

Error in creating Order Programmatically, Magento 2

I am creating order at controller action, just to test if its working or not as:

class Save extends \Magento\Framework\App\Action\Action {  /**     * @param Magento\Framework\App\Helper\Context $  context     * @param Magento\Store\Model\StoreManagerInterface $  storeManager     * @param Magento\Catalog\Model\Product $  product     * @param Magento\Framework\Data\Form\FormKey $  formKey $  formkey,     * @param Magento\Quote\Model\Quote $  quote,     * @param Magento\Customer\Model\CustomerFactory $  customerFactory,     * @param Magento\Sales\Model\Service\OrderService $  orderService,     */     public function __construct(         \Magento\Framework\App\Helper\Context $  context,         \Magento\Store\Model\StoreManagerInterface $  storeManager,         \Magento\Catalog\Model\Product $  product,         \Magento\Framework\Data\Form\FormKey $  formkey,         \Magento\Quote\Model\QuoteFactory $  quote,         \Magento\Quote\Model\QuoteManagement $  quoteManagement,         \Magento\Customer\Model\CustomerFactory $  customerFactory,         \Magento\Customer\Api\CustomerRepositoryInterface $  customerRepository,         \Magento\Sales\Model\Service\OrderService $  orderService       ) {         $  this->_storeManager = $  storeManager;         $  this->_product = $  product;         $  this->_formkey = $  formkey;         $  this->quote = $  quote;         $  this->quoteManagement = $  quoteManagement;         $  this->customerFactory = $  customerFactory;         $  this->customerRepository = $  customerRepository;         $  this->orderService = $  orderService;         parent::__construct($  context);     }      /**      * Create Order On Your Store      *       * @param array $  orderData      * @return array      *      */     public function createMageOrder($  orderData) {         $  store=$  this->_storeManager->getStore();         $  websiteId = $  this->_storeManager->getStore()->getWebsiteId();         $  customer=$  this->customerFactory->create();         $  customer->setWebsiteId($  websiteId);         $  customer->loadByEmail($  orderData['email']);// load customet by email address         263135         if(!$  customer->getEntityId()){             //If not avilable then create this customer              $  customer->setWebsiteId($  websiteId)                     ->setStore($  store)                     ->setFirstname($  orderData['shipping_address']['firstname'])                     ->setLastname($  orderData['shipping_address']['lastname'])                     ->setEmail($  orderData['email'])                      ->setPassword($  orderData['email']);             $  customer->save();         }         $  quote=$  this->quote->create(); //Create object of quote         $  quote->setStore($  store); //set store for which you create quote         // if you have allready buyer id then you can load customer directly          $  customer= $  this->customerRepository->getById($  customer->getEntityId());         $  quote->setCurrency();         $  quote->assignCustomer($  customer); //Assign quote to customer          //add items in quote         foreach($  orderData['items'] as $  item){             $  product=$  this->_product->load($  item['product_id']);             $  product->setPrice($  item['price']);             $  quote->addProduct(                 $  product,                 intval($  item['qty'])             );         }          //Set Address to quote         $  quote->getBillingAddress()->addData($  orderData['shipping_address']);         $  quote->getShippingAddress()->addData($  orderData['shipping_address']);          // Collect Rates and Set Shipping & Payment Method          $  shippingAddress=$  quote->getShippingAddress();         $  shippingAddress->setCollectShippingRates(true)                         ->collectShippingRates()                         ->setShippingMethod('freeshipping_freeshipping'); //shipping method         $  quote->setPaymentMethod('checkmo'); //payment method         $  quote->setInventoryProcessed(false); //not effetc inventory         $  quote->save(); //Now Save quote and your quote is ready          // Set Sales Order Payment         $  quote->getPayment()->importData(['method' => 'checkmo']);          // Collect Totals & Save Quote         $  quote->collectTotals()->save();          // Create Order From Quote         $  order = $  this->quoteManagement->submit($  quote);          $  order->setEmailSent(0);         $  increment_id = $  order->getRealOrderId();         if($  order->getEntityId()){             $  result['order_id']= $  order->getRealOrderId();         }else{             $  result=['error'=>1,'msg'=>'Your custom message'];         }         return $  result;     }     public function execute()     {         $  orderData=[                     'currency_id' => 'USD',                     'email' => 'user@w3classes.info', //customer email id                     'shipping_address' =>[                     'firstname' => 'Test', //address Details                     'lastname' => 'User',                     'street' => '123 main street',                     'city' => 'Demo',                     'country_id' => 'US',                     'region' => 'xxx', // replace with region                     'postcode' => 'XXXXX', // replace with real zip code                     'telephone' => '9999999999',                     'save_in_address_book' => 1 // If you want to save in address book                     ],                     'items'=> [ //array of products for which you want to create order.                     ['product_id'=>'5','qty'=>2]                     ]                     ];         $  orderID = $  this->createOrder($  orderData);        echo $  orderID;     $  resultRedirect = $  this->resultRedirectFactory->create();     $  resultRedirect->setPath('frontname/index/index');     return $  resultRedirect; } 

Almost all links available are explaining same:

https://www.w3classes.info/create-order-programatically-in-magento-2/ https://www.mageplaza.com/devdocs/magento-2-create-order-programmatically.html

but when I do this I am having error:

Fatal error: Uncaught TypeError: Argument 2 passed to Magento\Eav\Model\Attribute\Data\Text::validateLength() must be of the type string, null given, called in /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php on line 80 and defined in /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php:141 Stack trace: #0 /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php(80): Magento\Eav\Model\Attribute\Data\Text->validateLength(Object(Magento\Customer\Model\Attribute), NULL) #1 /var/www/html/vendor/magento/module-eav/Model/Validator/Attribute/Data.php(131): Magento\Eav\Model\Attribute\Data\Text->validateValue(NULL) #2 /var/www/html/vendor/magento/framework/Validator/Constraint.php(54): Magento\Eav\Model\Validator\Attribute\Data->isValid(Object(Magento\Customer\Model\Customer\Interceptor))

3 /var/www/html/vendor/magento/framework/Validator.php(59): Magento\Framework\Validator\Constraint->isValid(Object(Magento\Customer\Model\Customer\Interceptor))

4 /var/www/html/vendor/magento/ in /var/www/html/vendor/magento/module-eav/Model/Attribute/Data/Text.php

on line 141

I did setup:di:compile cache:flush generated deleted but not working.

Can somebody help to find issue please.

Programmatically reindexing by product ids results in Uncaught TypeError

I’ve got a custom module for importing/creating products programmatically. After products are imported I would like to reindex only the new product ids. See code below.

private function _reindexByProductIds($ ids, $ indexers) { foreach($ indexers as $ indexer) { $ index = $ this->_indexerRegistry->get($ indexer); if(!$ index->isScheduled()) { $ index->reindexList($ ids); } } }

$ ids is an array of imported ids and $ indexers is an array of all the indexer ids. This function results in an Uncaught TypeError when trying to reindex ‘catalog_product_flat’, but when I run the indexer:reindex command I don’t get this error. See error below.

Fatal error: Uncaught TypeError: Argument 2 passed to Magento\Catalog\Model\Indexer\Product\Flat\TableBuilder::_fillTemporaryEntityTable() must be of the type array, null given, called in /Users/robertbisschop/Documents/Development/www.magento-logictrade.nl.local/vendor/magento/module-catalog/Model/Indexer/Product/Flat/TableBuilder.php on line 93 and defined in /Users/robertbisschop/Documents/Development/www.magento-logictrade.nl.local/vendor/magento/module-catalog/Model/Indexer/Product/Flat/TableBuilder.php:219 Stack trace: #0 /Users/robertbisschop/Documents/Development/www.magento-logictrade.nl.local/vendor/magento/module-catalog/Model/Indexer/Product/Flat/TableBuilder.php(93): Magento\Catalog\Model\Indexer\Product\Flat\TableBuilder->_fillTemporaryEntityTable(‘catalog_product…’, NULL, Array) #1 /Users/robertbisschop/Documents/Development/www.magento-logictrade.nl.local/vendor/magento/module-catalog/Model/Indexer/Product/Flat/AbstractAction.php(152): Magento\Catalog\Model\Indexer\Product\Flat\TableBuilder->build(‘1’, A in /Users/robertbisschop/Documents/Development/www.magento-logictrade.nl.local/vendor/magento/module-catalog/Model/Indexer/Product/Flat/TableBuilder.php on line 219

I’ve been debugging for a while, but can’t figure out how to solve it. Any help is highly appreciated.

How to add Home Page url key for all scopes programmatically using Recurring.php magento 2

i tried to add Home Page url key programmatically using Recurring.php

Normally from Magento Admin backend:

STORES -> GENERAL -> Web -> Default Pages -> Default Web URL:

enter image description here

I tried using

Vendor/Module/Setup/Recurring.php

<?php  namespace Vendor\Module\Setup;  use Magento\Framework\Setup\InstallSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\App\Config\ScopeConfigInterface;   class Recurring implements InstallSchemaInterface {        const default_web_url  = 'cms';     protected $  _configInterface;          /**      *  @var \Magento\Framework\App\Config\Storage\WriterInterface      */     protected $  configWriter;      /**      *      * @param \Magento\Framework\App\Config\Storage\WriterInterface $  configWriter      */     public function __construct(         \Magento\Framework\App\Config\Storage\WriterInterface $  configWriter     ) {          $  this->configWriter = $  configWriter;       }      public function install(SchemaSetupInterface $  setup, ModuleContextInterface $  context)     {        $  value = self::default_web_url;        $  this->configWriter->save('web/default/front',  $  value, $  scope = ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $  scopeId = 0);      } } 

In my local this value is storing for all store view scopes($ scopeId = 0) but in our server it’s setting value for only one store view.

This is the issue i am facing here if anyone having any idea please guide me.

Thanks in Advance !!!!.