Environment.userName is Unknown in Hololens2 - hololens

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
}
}

Related

SharePoint Online CSOM

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.

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:

Windows Phone 8 (HTC 8X) Flashlight does not turn on(Without using camera)

As a newbie programmer I am going to ask a silly question. I want to turn on the flashlight of windows phone 8 without blinking (continous like other flashlight apps). Now I tried to use the sample example of
Reflection failure when attempting to access Microsoft.Phone.Media.Extended
but it did not work. I created a button called 'flash' and paste the code. It compiled fine, but my device HTC 8X does not turn on the flashlight even for a second. What I should do ?
The library & code I used :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Flashlight_V_0._1.Resources;
using Microsoft.Phone.Media;
using Windows.Phone.Media.Capture;
using Microsoft.Xna.Framework.Media;
using System.IO;
namespace Flashlight_V_0._1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
// get the AudioViceoCaptureDevice
var avDevice = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
}
}
I also tried this:
try
{
var _device = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First());
_device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
}
catch (Exception ex)
{
//
}
What am I doing wrong?
Sorry for late reply, got it ago but could not post.Sorry for that.
WP7/WP7.5 gives default to access all the sensors. But in WP8, you have to manually enable the sensors capability.
Go to the solution explorer.
Select the project.
Select Properties -> WMAppManifest.xml
Double Click on 'WMAppManifest.xml'
Select 'Capabilities'
Enable proper capability for app
To resolve my problem I had to enable two capabilities.
ID_CAP_ISV_CAMERA
ID_CAP_MICROPHONE
Thank YOU

Reusable generic LightSwitch screen with WCF RIA Services

I'm new to WCF RIA Services, and have been working with LightSwitch for 4 or so months now.
I created a generic screen to be used for editing lookup tables all over my LightSwitch application, mostly to learn how to create a generic screen that can be used with different entity sets on a dynamic basis.
The screen is pretty simple:
Opened with arguments similar to this:
Application.ShowLookupTypesList("StatusTypes", "StatusTypeId"); which correspond to the entity set for the lookup table in the database.
Here's my WCF RIA service code:
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Reflection;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Server;
namespace WCF_RIA_Project
{
public class LookupType
{
[Key]
public int TypeId { get; set; }
public string Name { get; set; }
}
public static class EntityInfo
{
public static Type Type;
public static PropertyInfo Key;
public static PropertyInfo Set;
}
public class WCF_RIA_Service : LinqToEntitiesDomainService<WCSEntities>
{
public IQueryable<LookupType> GetLookupTypesByEntitySet(string EntitySetName, string KeyName)
{
EntityInfo.Set = ObjectContext.GetType().GetProperty(EntitySetName);
EntityInfo.Type = EntityInfo.Set.PropertyType.GetGenericArguments().First();
EntityInfo.Key = EntityInfo.Type.GetProperty(KeyName);
return GetTypes();
}
[Query(IsDefault = true)]
public IQueryable<LookupType> GetTypes()
{
var set = (IEnumerable<EntityObject>)EntityInfo.Set.GetValue(ObjectContext, null);
var types = from e in set
select new LookupType
{
TypeId = (int)EntityInfo.Key.GetValue(e, null),
Name = (string)EntityInfo.Type.GetProperty("Name").GetValue(e, null)
};
return types.AsQueryable();
}
public void InsertLookupType(LookupType lookupType)
{
dynamic e = Activator.CreateInstance(EntityInfo.Type);
EntityInfo.Key.SetValue(e, lookupType.TypeId, null);
e.Name = lookupType.Name;
dynamic set = EntityInfo.Set.GetValue(ObjectContext, null);
set.AddObject(e);
}
public void UpdateLookupType(LookupType currentLookupType)
{
var set = (IEnumerable<EntityObject>)EntityInfo.Set.GetValue(ObjectContext, null);
dynamic modified = set.FirstOrDefault(t => (int)EntityInfo.Key.GetValue(t, null) == currentLookupType.TypeId);
modified.Name = currentLookupType.Name;
}
public void DeleteLookupType(LookupType lookupType)
{
var set = (IEnumerable<EntityObject>)EntityInfo.Set.GetValue(ObjectContext, null);
var e = set.FirstOrDefault(t => (int)EntityInfo.Key.GetValue(t, null) == lookupType.TypeId);
Debug.Assert(e.EntityState != EntityState.Detached, "Entity was in a detached state.");
ObjectContext.ObjectStateManager.ChangeObjectState(e, EntityState.Deleted);
}
}
}
When I add an item to the list from the running screen, save it, then edit it and resave, I receive data conflict "Another user has deleted this record."
I can workaround this by reloading the query after save, but it's awkward.
If I remove, save, then readd and save an item with the same name I get unable to save data, "The context is already tracking a different entity with the same resource Uri."
Both of these problems only affect my generic screen using WCF RIA Services. When I build a ListDetail screen for a specific database entity there are no problems. It seems I'm missing some logic, any ideas?
I've learned that this the wrong approach to using LightSwitch.
There are several behind-the-scenes things this generic screen won't fully emulate and may not be do-able without quite a bit of work. The errors I've received are just one example. LightSwitch's built-in conflict resolution will also fail.
LS's RAD design means just creating a bunch of similar screens is the way to go, with some shared methods. If the actual layout needs changed across many identical screens at once, you can always find & replace the .lsml files if you're careful and make backups first. Note that modifying these files directly isn't supported.
I got that error recently. In my case I create a unique ID in my WCF RIA service, but in my screen behind code I must explicitly set a unique ID when I create the object that will later be passed to the WCF RIA Service insert method (this value will then be overwritten with the unique counter ID in the table of the underlying database).
See the sample code for this project:
http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/157/A-Visual-Studio-LightSwitch-Picture-File-Manager.aspx

Sharepoint Custom Filter Web Part

I want to create a custom web part that has more than 1 filter web part and that can be connected to Report Viewer Web Part (Integrated Mode) at runtime/design time.
I searched a lot for this, but could not find a way to have single web part that is a provider to more than 1 filters.
Say for example -
My Report accepts 2 parameter Department and Region. 
I want to connect both parameters with single web part having two drop down (one for Department and one for Region)
Values from both the drop down should be passed to Department and Region
Report should be rendered in Report Viewer Web Part
Solution Tried so far
Create a web part that adds two custom drop down
Custom drop down class that implements from ITransformableFilterValues
Have 2 methods on the web pat each having ConnectionProvider attribute and return instance of drop down control
Problem:
Even though 2 connection option is shown on my custom filter web part only one can be added.
For example if I connect Filter1(custom web part) to Department then I am unable to connect it to Report Viewer web part again.
My web part have methods like this:
 
[ConnectionProvider("Departmet", "UniqueIDForDept", AllowsMultipleConnections = true)] 
public ITransformableFilterValues ReturnCity() 
{ 
return dropDownDepartment; // It implemets ITransformableFilterValues 
} 
[ConnectionProvider("Region", "UniqueIDForRegion", AllowsMultipleConnections = true)] 
public ITransformableFilterValues ReturnMyRegionB() 
{ 
return dropDownRegion; //It implemets ITransformableFilterValues 
}
I did something similar. This might help point you in the right direction. I used data in a form library to create a detailed report. I used reporting services and connected to sharepoint using web services. http://server/_vti_bin/Lists.asmx. The report parameter I used was the item ID or GUID. Then I configured my report viewer. On the form library I used JavaScript to override the context menu to add "View Report". On the report page I used a Query String filter to grab the item ID out of the url.
Not sure if you were able to fix your problem..
Actually I tried with AllowsMultipleConnections = true and it worked fine:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using aspnetwebparts = System.Web.UI.WebControls.WebParts;
using Microsoft.Office.Server.Utilities;
using wsswebparts = Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Portal.WebControls;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Microsoft.SharePoint.Utilities;
namespace FromMultiSource
{
[Guid("a0d068dd-9475-4055-a219-88513e173502")]
public class MultiSource : aspnetwebparts.WebPart
{
List<wsswebparts.IFilterValues> providers = new List<wsswebparts.IFilterValues>();
public MultiSource()
{
}
[aspnetwebparts.ConnectionConsumer("Multiple Source Consumer", "IFilterValues", AllowsMultipleConnections = true)]
public void SetConnectionInterface(wsswebparts.IFilterValues provider)
{
this.providers.Add(provider);
if (provider != null)
{
List<wsswebparts.ConsumerParameter> l = new List<wsswebparts.ConsumerParameter>();
l.Add (new wsswebparts.ConsumerParameter ("Value", wsswebparts.ConsumerParameterCapabilities.SupportsMultipleValues | Microsoft.SharePoint.WebPartPages.ConsumerParameterCapabilities.SupportsAllValue));
provider.SetConsumerParameters(new ReadOnlyCollection<wsswebparts.ConsumerParameter>(l));
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
// TODO: add custom rendering code here.
// Label label = new Label();
// label.Text = "Hello World";
// this.Controls.Add(label);
}
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
this.EnsureChildControls();
foreach (wsswebparts.IFilterValues provider in this.providers)
{
if (provider != null)
{
string prop = provider.ParameterName;
ReadOnlyCollection<string> values = provider.ParameterValues;
if (prop != null && values != null)
{
writer.Write("<div>" + SPEncode.HtmlEncode(prop) + ":</div>");
foreach (string v in values)
{
if (v == null)
{
writer.Write("<div> <i>"(empty)"/null</i></div>");
}
else if (v.Length == 0)
{
writer.Write("<div> <i>empty string</i></div>");
}
else
{
writer.Write("<div> " + v + "</div>");
}
}
}
else
{
writer.Write("<div>No filter specified (all).</div>");
}
}
else
{
writer.Write("<div>Not connected.</div>");
}
writer.Write("<hr>");
}
}
}
}

Resources