SharePoint Online CSOM - sharepoint

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
namespace Testmyproject
{
class Program
{
static void Main(string[] args)
{
string userName = "pratapbangosavi#xqsnt.onmicrosoft.com";
Console.WriteLine("Enter Your Password Please ------- ");
SecureString password = GetPasswordOfYourSite();
// ClienContext - Get the context for the SharePoint Online Site
using (var clientContext = new
ClientContext("https://xqsnt.sharepoint.com/sites/mysite/"))
{
// SharePoint Online Credentials
clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
// Get the SharePoint web
Web web = clientContext.Web;
// Load the Web properties
clientContext.Load(web);
// Execute the query to the server.
clientContext.ExecuteQuery();
// Web properties - Display the Title and URL for the web
Console.WriteLine("Title: " + web.Title);
Console.WriteLine("URL: " + web.Url);
Console.WriteLine("Template: " + web.WebTemplate);
Console.ReadLine();
}
}
private static SecureString GetPasswordOfYourSite()
{
ConsoleKeyInfo info;
//Get the user's password as a SecureString
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
}
If you are trying to run CSOM against SharePoint Online and gets the error below.
All Contents are correct as like Site URL, Username and password.
I need to display SharePoint Site Title, URL and Template but show Error at clientContext.ExecuteQuery();
enter image description here

Please check your .NET Framework version. Please change the version to 4.6 or later to resolve this issue. If you are using .NET Framework under 4.6. You can add the following code to resolve this issue:
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
Hope it can help you. Thanks for your understanding.

Related

Azure Cognitive Service\Computer Visio\OCR - Can I use it into into WebSite C#

I'm trying to use Azure Ocr into my website c#.
I added the package Microsoft.Azure.CognitiveServices.Vision.ComputerVision and I wrote code, with key and endpoint of my subscription.
static string subscriptionKey = "mykey";
static string endpoint = "https://myocr.cognitiveservices.azure.com/";
private const string ANALYZE_URL_IMAGE = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/printed_text.jpg";
protected void Page_Load(object sender, EventArgs e)
{
// Create a client
ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
// Analyze an image to get features and other properties.
AnalyzeImageUrl(client, ANALYZE_URL_IMAGE).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task AnalyzeImageUrl(ComputerVisionClient client, string imageUrl)
{
// Read text from URL
var textHeaders = await client.ReadAsync(imageUrl);
...
}
It seems all ok, but at line
var textHeaders = await client.ReadAsync(urlFile);
website crashes.
I don't understand why. No error, it's just stopped.
So I ask: azure ocr can to be use only with console app?
EDIT
The code is ok for ConsoleApp and WebApp but not working for my asp.net WEBSITE.
Could be a problem with async?
We can use OCR with web app also,I have taken the .net core 3.1 webapp in Visual Studio and installed the dependency of Microsoft.Azure.CognitiveServices.Vision.ComputerVision by selecting the check mark of include prerelease as shown in the below image:
After creating computer vision resource in Azure Portal, copied the key and endpoint from there and used inside the c# code.
using System;
using System.Collections.Generic;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Linq;
namespace ComputerVisionQuickstart
{
class Program
{
// Add your Computer Vision subscription key and endpoint
static string subscriptionKey = "c1****b********";
static string endpoint = ".abc.cognitiveservices.azure.com/";
private const string READ_TEXT_URL_IMAGE = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/printed_text.jpg";
static void Main(string[] args)
{
Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
Console.WriteLine();
ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
// Extract text (OCR) from a URL image using the Read API
ReadFileUrl(client, READ_TEXT_URL_IMAGE).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile)
{
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("READ FILE FROM URL");
Console.WriteLine();
// Read text from URL
var textHeaders = await client.ReadAsync(urlFile);
// After the request, get the operation location (operation ID)
string operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
// Retrieve the URI where the extracted text will be stored from the Operation-Location header.
// We only need the ID and not the full URL
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
// Extract the text
ReadOperationResult results;
Console.WriteLine($"Extracting text from URL file {Path.GetFileName(urlFile)}...");
Console.WriteLine();
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
}
while ((results.Status == OperationStatusCodes.Running ||
results.Status == OperationStatusCodes.NotStarted));
// Display the found text.
Console.WriteLine();
var textUrlFileResults = results.AnalyzeResult.ReadResults;
foreach (ReadResult page in textUrlFileResults)
{
foreach (Line line in page.Lines)
{
Console.WriteLine(line.Text);
}
}
Console.WriteLine();
}
}
}
The above code is taken from the Microsoft Document.
I can be able to read the text inside the image successfully as shown in the below screenshot:

Environment.userName is Unknown in Hololens2

I have an hololens2 application that I built in Unity. The Environment.Username works in the Unity editor correctly, but when I deployed to the HL2, the Environment.UserName is Unknown. Under the player settings I've applied Enterprise Application, WebCam,Microphone, HumanInterfaceDevice, UserAccountInformation, Bluetooth, SystemManagement, UserDataTasks and Contacts.
It builds just fine and deploys to HL2 without problems, but the UserName is Unknown. When I go to the HL2 start menu, it displays my name correctly.
Please Help,
Martin F.
Please try the following code, it should display the account name signed into the HoloLens2:
using System;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;
#if WINDOWS_UWP
using Windows.System;
#endif
public class UserName : MonoBehaviour
{
[SerializeField]
private TMP_Text userNameText = null;
// Start is called before the first frame update
async void Start()
{
#if WINDOWS_UWP
IReadOnlyList<User> users = await User.FindAllAsync();
StringBuilder sb = new StringBuilder();
foreach (User u in users)
{
string name = (string)await u.GetPropertyAsync(KnownUserProperties.AccountName);
if (string.IsNullOrWhiteSpace(name))
{
name = "unknown account name";
}
sb.AppendLine(name);
}
userNameText.text = sb.ToString();
#endif
}
}

Inference for custom vision model hosted on Azure Cognitive Services stopped working in December for me

I have a service that has been successfully performing inferences for 2 years, but API stopped working in December. I have created a simple App based on documentation from Microsoft to reproduce the problem. Please see code below.
Is anybody else experience this problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction;
using static System.Net.Mime.MediaTypeNames;
namespace TestCustomVision
{
class Program
{
public static void Main()
{
string imageFilePath = <My Image>;
MakePredictionRequest(imageFilePath).Wait();
Console.WriteLine("\n\nHit ENTER to exit...");
Console.ReadLine();
}
public static async Task MakePredictionRequest(string imageFilePath)
{
var client = new HttpClient();
// Request headers - replace this example key with your valid Prediction-Key.
client.DefaultRequestHeaders.Add("Prediction-Key", <My key>);
// Prediction URL - replace this example URL with your valid Prediction URL.
string url = <Prediction URL>;
HttpResponseMessage response;
// Request body. Try this sample with a locally stored image.
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(url, content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
private static byte[] GetImageAsByteArray(string imageFilePath)
{
FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
}
}

how to run an exe file on release in VSTS

I have created a console application for fetching the SharePoint site title inside visual studio online. The url of the SharePoint site is passed along in the code, but the password needs to entered in at console window on the run-time.
Then i have defined the build definition and is able to build the solution and copy the files to the artifact.
And i configured the release definition, and i am trying to run the build-ed .exe file, but is getting the bellow error:
Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file.
PS: I have defined a variable $pass and then added it in the arguments section for getting the password of the SharePoint site.
variable declaration:
Error Screen which i am getting:
Code for the console app:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
namespace VSTS_Demo_App
{
class Program
{
static void Main(string[] args)
{
string userName = "$$$#$$$.onmicrosoft.com";
Console.WriteLine("Enter your password.");
SecureString password = GetPassword();
// ClienContext - Get the context for the SharePoint Online Site
// SharePoint site URL - https://c986.sharepoint.com
using (var clientContext = new ClientContext("https://$$$$$$$$$$$$$$$$$$$$$$$$$$"))
{
// SharePoint Online Credentials
clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
// Get the SharePoint web
Web web = clientContext.Web;
// Load the Web properties
clientContext.Load(web);
// Execute the query to the server.
clientContext.ExecuteQuery();
// Web properties - Display the Title and URL for the web
Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
Console.ReadLine();
}
}
private static SecureString GetPassword()
{
ConsoleKeyInfo info;
Console.WriteLine("get passwod -called");
//Get the user's password as a SecureString
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
}
The problem is with you Console.ReadLine() methods.
When running a build, vsts redirects the console input and output.
Your code is breaking here info = Console.ReadKey(true);, based on the stack trace you provided.
You are passing it via args, but you are not using it.
Change your code to:
SecureString password;
if (args.length > 0)
{
password = args;
}
else
{
password = GetPassword();
}
I didn't test if password = args will work directly or if you need to append chars. That I will leave to you.
Update your code like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
namespace VSTS_Demo_App
{
class Program
{
static void Main(string[] args)
{
string userName = "$$$#$$$.onmicrosoft.com";
Console.WriteLine("Enter your password.");
SecureString password = GetPassword(args);
// ClienContext - Get the context for the SharePoint Online Site
// SharePoint site URL - https://c986.sharepoint.com
using (var clientContext = new ClientContext("https://$$$$$$$$$$$$$$$$$$$$$$$$$$"))
{
// SharePoint Online Credentials
clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
// Get the SharePoint web
Web web = clientContext.Web;
// Load the Web properties
clientContext.Load(web);
// Execute the query to the server.
clientContext.ExecuteQuery();
// Web properties - Display the Title and URL for the web
Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
//Console.ReadLine();
}
}
private static SecureString GetPassword(string[] args)
{
ConsoleKeyInfo info;
Console.WriteLine("get passwod -called");
//Get the user's password as a SecureString
SecureString securePassword = new SecureString();
if (args.length > 0)
{
char[] cs= args[0].ToCharArray();
foreach(char c in cs)
{
securePassword.AppendChar(c);
}
}
else
{
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
}
return securePassword;
}
}
}

Sharepoint: How do i find a mail enabled list, if i only have the email?

I know the email from a mail enabled list, with I have no idea where the list lies.
How do i find the list to which the email belongs to?
The code below works if you know the site collection of the list. If you don't know that, you can easily modify the code to loop a complete web application (or even a complete farm):
using System;
using Microsoft.SharePoint;
namespace FindListByEmail
{
class Program
{
static void Main(string[] args)
{
string siteUrl = "[complete this]";
string email = "[complete this]"; // only the part before the #
using (SPSite site = new SPSite(siteUrl))
{
foreach (SPWeb web in site.AllWebs)
{
try
{
foreach (SPList list in web.Lists)
{
if (list.CanReceiveEmail)
{
if (list.EmailAlias != null && list.EmailAlias.Equals(email, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("The email belongs to list {0} in web {1}", list.Title, web.Url);
Console.ReadLine();
return;
}
}
}
}
finally
{
if (web != null)
{
web.Dispose();
}
}
}
}
}
}
}
To find All Incoming E-Mail Enabled Lists and Libraries in SharePoint, You can use PowerShell , C# code or SQL Server Query!
Find the PowerShell Script, SQL Query and C# code here: http://www.sharepointdiary.com/2011/06/find-all-incoming-email-enabled-lists.html#ixzz2aKvhRTDN

Resources