Sharepoint Object Model applicaton cannot run outside of WSS server - sharepoint

I create a C# console application using Microsoft.SharePoint object model VS WSS extensions on Windows Server 2003. The application is supposed to iterate WSS3.0 sites looking for all available lists. It runs just fine on the server. But if I try to run the exe from another computer on the network, the application crashes instantly on SPSite siteCollection = new SPSite("http://devsharepoint);
Even my try and catch doesn't help as catch is not executed.
Is it intended to run the Sharepoint object model applications only on machines with VS SharePoint extensions installed?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace ConsoleApplicationWSSobjectModel
{
class Program
{
static void Main(string[] args)
{
string url = "http://sharepoint";
Console.WriteLine("Trying to access: " + url);
try
{
SPSite siteCollection = new SPSite(url);//"http://Server_Name");
SPWebCollection sites = siteCollection.AllWebs;
foreach (SPWeb site in sites)
{
SPListCollection lists = site.Lists;
Console.WriteLine("Site: " + site.Name + " Lists: " + lists.Count.ToString());
}
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

You cannot use the SP object model ”outside sharepoint” you will have to use web services (or if your go with sharepoint 2010 you can use the new client object model)

Anything built with the SharePoint object model can only run on a server with SharePoint installed. There is however no dependency on the VS extensions.

You can use Client Object Model using C# or VB as your language. Add references Microsoft.sharepoint.client.dll and Microsoft.sharepoint.client.Runtime.dll it can be found under 14(SP2010) or 15(SP2013) hive ISAPI folder.

Related

Excel to DataSet using OLEDB working differently between .NET Core and .NET Framework

I have a worker service that references a .NET Framework class library. The class library contains a method to convert Excel to a dataset.
While debugging on Visual Studio, everything works as expected, but after publishing I get the error message:
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
To debug, I built the below two console apps with exactly the same code—one in .NET Core, the other .NET Framework. I then run the projects on two computers.
Computer A: Microsoft Office Tools installed, but no AccessDatabaseEngine.exe
Computer B: No Microsoft Office Tools, AccessDatabaseEngine installed
using System;
using System.Data;
using System.Data.OleDb;
using System.Text;
namespace ToDataSheetCore
{
class Program
{
static void Main(string[] args)
{
DataSet dt2 = ExcelToDataSetCommon("C:\\pathToExcel\\excelFile - AUGUST 04 2021.xlsx");
StringBuilder sb2 = new StringBuilder();
foreach (DataTable table in dt2.Tables)
{
foreach (DataRow row in table.Rows)
{
sb2.Append(string.Join(" ", row.ItemArray));
sb2.AppendLine();
}
}
Console.WriteLine(sb2);
Console.ReadLine();
}
public static DataSet ExcelToDataSetCommon(string SourceFilename)
{
DataSet ds = new DataSet();
try
{
string connStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;\"", SourceFilename);
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
DataTable schemaDT = conn.GetSchema("Tables", new string[] { null, null, null, "TABLE" });
conn.Close();
string tableName = schemaDT.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM [{0}]", tableName), conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(ds);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
return ds;
}
}
}
Result
Computer A
.NET Core
Debug mode
Prints excel content to console
Publish mode - self-contained(win64, anypc)
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
.NET Framework
Debug mode
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Publish mode - self-contained
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Computer B
.NET Core
Debug mode
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Publish mode - self-contained(win64, anypc)
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
.NET Framework
Debug mode
Prints excel content to console (Fails on uninstalling AccessDatabaseEngine)
Publish mode - self-contained
Prints excel content to console (Fails on uninstalling AccessDatabaseEngine)
I understand installing AccessDatabaseEngine provider has an effect, but I don't understand the different results from .NET Framework and .NET Core.
Though I have resorted to using ExcelDataReader since I want to avoid external dependencies.
I am confused by the difference in the results using OleDB API between .NET Core and .NET Framework. Is there a way the AccessDatabaseEngine provider can be published together with a .NET project?

Need help to develop simple Sharepoint 2013 app to upload excel files to a library

I spun up a new windows 2012 Server R2, installed Sharepoint 2013, and Visual Studio 2019 with the Office/Sharepoint dev options on an old Dell server. I'm trying to write and debug an app I found on the web to upload excel files from a shared drive to a sharepoint document library. I'm at the point where everytime I try to run this app, I get an error stating:
The Web application at http://tcaserver01/my/MPR could not be found.
Verify that you have typed the URL correctly. If the URL should be
serving existing content, the system administrator may need to add a
new request URL mapping to the intended application.
I just need a bit of hand-holding to get things properly configured I think. However, when I put in the url in a web browser, it shows the empty library fine.
using System;
using System.IO;
using Microsoft.SharePoint;
namespace SPTest2
{
class Program
{
[STAThread]
static int Main(string[] args)
{
String site = "http://tcaserver01/my/MPR"; //URL of SharePoint site
String library = "Review_Workbooks"; //Library Name
String filePath = #"S:\MPR\MPR Template.xlsx"; //Entire path of file to upload
try
{
using (SPSite spSite = new SPSite(site))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
//Check if file exists in specified path
if (!System.IO.File.Exists(filePath))
Console.WriteLine("Error - Specified file not found.");
//Get handle of library
SPFolder spLibrary = spWeb.Folders[library];
//Extract file name (file will be uploaded with this name)
String fileName = System.IO.Path.GetFileName(filePath);
//Read file for uploading
FileStream fileStream = File.OpenRead(filePath);
//Replace existing file
Boolean replaceExistingFile = true;
//Upload document to library
SPFile spfile = spLibrary.Files.Add(fileName, fileStream, replaceExistingFile);
spfile.CheckIn("file uploaded via code");
spLibrary.Update();
}
}
Console.WriteLine("File uploaded successfully !!");
Console.ReadLine();
}
catch (Exception exp)
{
Console.WriteLine("Error uploading file - " + exp.Message);
Console.ReadLine();
}
return 0;
}
}
}
Well, it seems when I logged in as the Sharepoint admin user account, I was able to move further in the app, successfully opening up the Sharepoint site. So, when I was logged in as myself, I must not have had the appropriate permissions to open the site. So, this question should be closed as I can now get past what was blocking me. Thanks for anyone who may have read this question already!

Restart Web/Api-App on Azure programmatically

How can I restart Web-Apps and API-Apps on Azure programmatically?
(I'd like to call it from another API-App within the same App service plan.)
There's also the "Microsoft Azure Management Libraries" Nuget that allows you to work with Azure services from inside of applications.
See this page for an example on how to create new web sites from inside of an Azure Web site. Restarting web services work in a similar way to creating new services. See this page for a list of available web site related methods.
Also, for authenticating is used certificate base authentication, see this page for more details on that.
Bellow is a short command line program that will restart all websites in all the webspaces you got in your Azure subscription. It works kinda like an iisreset for Azure Web Sites.
The code is based on samples taken from the links earlier mentioned:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.WebSites;
using Microsoft.WindowsAzure;
using System.Security.Cryptography.X509Certificates;
using Microsoft.WindowsAzure.Management.WebSites.Models;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var subscriptionId = "[INSERT_YOUR_SUBSCRIPTION_ID_HERE]";
var cred = new CertificateCloudCredentials(subscriptionId, GetCertificate());
var client = new WebSiteManagementClient(cred);
WebSpacesListResponse webspaces = client.WebSpaces.List();
webspaces.Select(p =>
{
Console.WriteLine("Processing webspace {0}", p.Name);
WebSpacesListWebSitesResponse websitesInWebspace = client.WebSpaces.ListWebSites(p.Name,
new WebSiteListParameters()
{
});
websitesInWebspace.Select(o =>
{
Console.Write(" - Restarting {0} ... ", o.Name);
OperationResponse operation = client.WebSites.Restart(p.Name, o.Name);
Console.WriteLine(operation.StatusCode.ToString());
return o;
}).ToArray();
return p;
}).ToArray();
if(System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Press anykey to exit");
Console.Read();
}
}
private static X509Certificate2 GetCertificate()
{
string certPath = Environment.CurrentDirectory + "\\" + "[NAME_OF_PFX_CERTIFICATE]";
var x509Cert = new X509Certificate2(certPath,"[PASSWORD_FOR_PFX_CERTIFICATE]");
return x509Cert;
}
}
}
Another alternative, if you can't find the function you need from the above mentioned library, you can also run powershell commands programmatically from inside of your application. You most likely will need to move, the application that is supposed to run these cmdlets, to a virtual machine to be able to load the needed powershell modules. See this page for more information on running powershell cmdlets programmatically.
You can use Powershell to do this. The relevant commands are:
Start-AzureWebsite -Name “xxxx”
Stop-AzureWebsite -Name “xxxx”
You can find help on these commands at the following links:
https://msdn.microsoft.com/en-us/library/azure/dn495288.aspx
https://msdn.microsoft.com/en-us/library/azure/dn495185.aspx
I think handling the base REST API is much better option. The Azure SDK changes quite a lot and lacks good documentation.
Here is an up-to-date sample code:
https://github.com/davidebbo/AzureWebsitesSamples/
You can adapt it to your needs.

Enumerate SharePoint 2010 Groups Using C#

I want to enumerate all of the Groups in my SharePoint 2010 site using Visual Studio 2010 and C#. I don't want to create anything that needs to be deployed unless it's absolutely necessary. Is there a way to, basically, connect to the SharePoint instance and interrogate it for Groups and other objects without deploying anything?
Please don't respond with a PowerShell script. I want to do this using Visual Studio and C#.
Thanks,
Doug
Using the SharePoint 2010 Client Object Model (2010 & 2013) you can write something like this:
static void Main(string[] args)
{
var ctx = new ClientContext("http://server");
ctx.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
ctx.Load(ctx.Web.SiteGroups);
ctx.ExecuteQuery();
foreach (Group g in ctx.Web.SiteGroups)
{
Console.WriteLine(g.LoginName);
}
}

SharePoint 2010: feature receiver code executed from UI, not from PowerShell or stdadm

I have a WSP containing a web scope feature with the following code:
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
namespace Macaw.DualLayout.Samples.Features.DualLayoutSampleEmpty_Web
{
[Guid("8b558382-5566-43a4-85fa-ca86845b04b0")]
public class DualLayoutSampleEmpty_WebEventReceiver : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPWeb web = (SPWeb)properties.Feature.Parent)
{
using (SPSite site = (SPSite)web.Site)
{
Uri uri = new Uri(site.Url + "/_catalogs/masterpage/DLSampleEmpty.master");
web.CustomMasterUrl = uri.AbsolutePath; // Master for all publishing pages
web.Update();
}
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
using (SPWeb web = (SPWeb)properties.Feature.Parent)
{
using (SPSite site = (SPSite)web.Site)
{
Uri uri = new Uri(site.Url + "/_catalogs/masterpage/v4.master");
web.CustomMasterUrl = uri.AbsolutePath; // Master for all publishing pages
web.Update();
}
}
}
}
}
I do F5 deployment from Visual Studio 2010.
When I activate the feature from UI I get into my breakpoint in the feature code, the feature code is executed.
When I activate the feature from PowerShell:
Enable-SPFeature -Url http://myserver/sites/publishing/empty -Identity MyFeatureName -force -verbose
or with STSADM:
stsadm -o activatefeature -name MyFeatureName -url http://myserver/sites/Publishing/Empty -force
I see that the feature is activated (in the UI), but I don't hit my breakpoint and the feature receiver code is NOT executed.
Any ideas?
If you use powershell or stsadm the feature will not run in the context of the IIS worker process. What do you attach VS studio to when you debug?
When debugging stsadm tasks I usually add:
System.Diagnostics.Debugger.Launch();
to the code and you will be prompted to attach a debugger when the command is run. Crude but easy. (Don't forget to remove)
-"By default, when you run a Visual Studio SharePoint application, its features are automatically activated for you on the SharePoint server. However, this causes problems when you debug feature event receivers, because when a feature is activated by Visual Studio, it runs in a different process than the debugger. This means that some debugging functionality, such as breakpoints, will not work correctly.
To disable the automatic activation of the feature in SharePoint and allow proper debugging of Feature Event Receivers, set the value of the project's Active Deployment Configuration property to No Activation before debugging. Then, after your Visual Studio SharePoint application is running, manually activate the feature in SharePoint. To do this, click Site Settings on the Site Actions menu in SharePoint, click the Manage Site Features link, and then click the Activate button next to the feature and resume debugging as normal."
Source: http://msdn.microsoft.com/en-us/library/ee231550.aspx

Resources