how to check outlook is configured for current user - c#-4.0

I want to check if outlook is installed on given machine and configured for current user. I am using below code...
private static bool IsOutlookProfileConfigured2()
{
try
{
RegistryKey currentUser = Registry.CurrentUser;
RegistryKey regWMSprofile = currentUser.OpenSubKey
(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles");
if (regWMSprofile == null)
{
regWMSprofile = currentUser.OpenSubKey
(#"Software\Microsoft\Office\15.0\Outlook\Profiles");
if (regWMSprofile == null)
{
return false;
}
Console.WriteLine(#"Found on path==>Software\Microsoft\Office\15.0\Outlook\Profiles");
}
else
{
Console.WriteLine(#"Found on path==>SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles");
}
Outlook.Application OlApplication = new Outlook.Application();
if (regWMSprofile.SubKeyCount > 0)
{
if (OlApplication == null)
{
return false;
}
Outlook.NameSpace olNameSpace =
OlApplication.GetNamespace("MAPI");
if (olNameSpace != null && olNameSpace.Accounts !=
null && olNameSpace.Accounts.Count > 0)
{
return true;
}
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
return false;
}
method is saying outlook profile is found at "Software\Microsoft\Office\15.0\Outlook\Profiles".
Outlook 2013 is installed on users machine but not configured.
so this method opens outlook profile configuration wizard.
Can anyone help me with fixing this function or some sample code that will check if outlook is configured for current user and should not start profile configuration wizard.
Thanks in advance.

If you find any folder inside this 'Profiles' folder, then the Outlook
is configured for the current user.
HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows
Messaging Subsystem\Profiles
Check link:- How to detect whether Outlook is configured on machine using Regis

Related

What is the new button name for Base.Actions["LSPOReceiptLine_binLotSerial"].Press()?

I have inherited an older customization to the Purchase Receipts / PO302000 screen that I'm trying to upgrade, and it had customization code to import Lot/Serial nbrs from an Excel spreadsheet. It all seems to work alright, except that at the end, it errors out when pressing a button as follows:
Base.Actions["LSPOReceiptLine_binLotSerial"].Press();
Here's the entire code:
public virtual void importAllocations()
{
try
{
if (Base.transactions.Current != null)
{
var siteid = Base.transactions.Current.SiteID;
if (Base.splits.Select().Count == 0)
{
if (this.NewRevisionPanel.AskExt() == WebDialogResult.OK)
{
const string PanelSessionKey = "ImportStatementProtoFile";
PX.SM.FileInfo info = PX.Common.PXContext.SessionTyped<PXSessionStatePXData>().FileInfo[PanelSessionKey] as PX.SM.FileInfo;
System.Web.HttpContext.Current.Session.Remove(PanelSessionKey);
if (info != null)
{
byte[] filedata = info.BinData;
using (NVExcelReader reader = new NVExcelReader())
{
Dictionary<UInt32, string[]> data = reader.loadWorksheet(filedata);
foreach (string[] textArray in data.Values)
{
if (textArray[0] != GetInventoryCD(Base.transactions.Current.InventoryID))
{
throw (new Exception("InventoryID in file does not match row Inventory ID"));
}
else
{
//Find the location ID based on the location CD provided by the Excel sheet...
INLocation inloc = PXSelect<INLocation,
Where<INLocation.locationCD, Equal<Required<INLocation.locationCD>>,
And<INLocation.siteID, Equal<Required<INLocation.siteID>>>>>.Select(Base
, textArray[1]
, Base.transactions.Current.SiteID);
Base.splits.Insert(new POReceiptLineSplit()
{
InventoryID = Base.transactions.Current.InventoryID,
LocationID = inloc.LocationID, //Convert.ToInt32(textArray[1]), //Base.transactions.Current.LocationID,
LotSerialNbr = textArray[2],
Qty = Decimal.Parse(textArray[3])
});
}
}
}
}
}
}
}
Base.Actions["LSPOReceiptLine_binLotSerial"].Press();
}
catch (FileFormatException fileFormat)
{
// Acuminator disable once PX1053 ConcatenationPriorLocalization [Justification]
throw new PXException(String.Format("Incorrect file format. File must be of type .xlsx", fileFormat.Message));
}
catch (Exception ex)
{
throw ex;
}
}
Now, there seems to be no such button - and I have no idea what it would be called now, or if it even still exists. I don't even really know what this action did.
Any ideas?
Thanks much...
That logic has been moved into the PX.Objects.PO.GraphExtensions.POReceiptEntryExt.POReceiptLineSplittingExtension. That action was doing the following in the PX.Objects.PO.LSPOReceiptLine
// PX.Objects.PO.LSPOReceiptLine
// Token: 0x0600446F RID: 17519 RVA: 0x000EE86C File Offset: 0x000ECA6C
public override IEnumerable BinLotSerial(PXAdapter adapter)
{
if (base.MasterCache.Current != null)
{
if (!this.IsLSEntryEnabled((POReceiptLine)base.MasterCache.Current))
{
throw new PXSetPropertyException("The Line Details dialog box cannot be opened because changing line details is not allowed for the selected item.");
}
this.View.AskExt(true);
}
return adapter.Get();
}
Now it is called ShowSplits and is part of the POReceiptLineSplittingExtension extension.
// PX.Objects.PO.GraphExtensions.POReceiptEntryExt.POReceiptLineSplittingExtension
// Token: 0x06005359 RID: 21337 RVA: 0x00138621 File Offset: 0x00136821
public override IEnumerable ShowSplits(PXAdapter adapter)
{
if (base.LineCurrent == null)
{
return adapter.Get();
}
if (!this.IsLSEntryEnabled(base.LineCurrent))
{
throw new PXSetPropertyException("The Line Details dialog box cannot be opened because changing line details is not allowed for the selected item.");
}
return base.ShowSplits(adapter);
}
Given the fact that ShowSplits is defined in the LineSplittingExtension originally it may be referred to as "LineSplittingExteions_ShowSplits" or "POReceiptLineSplittingExtension_ShowSplits". I would suggest including that POReceiptLineSplittingExtension as part of your extension and simply call the Base1.ShowSplits

Azure cognitive Service - Speech sample code failed with authentication error

The program returns: CANCELED: Reason=Error ErrorDetails=WebSocket Upgrade failed with an authentication error (401). Please check for correct subscription key (or authorization token) and region name. SessionId: cbfcdf7f26304343a08de6c398652053
I'm using my free trial subscription key and westus region. This is the sample code found here: https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-microphone?tabs=unity%2Cx-android%2Clinux%2Cjava-runtime&pivots=programming-language-csharp
using UnityEngine;
using UnityEngine.UI;
using Microsoft.CognitiveServices.Speech;
#if PLATFORM_ANDROID
using UnityEngine.Android;
#endif
#if PLATFORM_IOS
using UnityEngine.iOS;
using System.Collections;
#endif
public class Helloworld : MonoBehaviour
{
// Hook up the two properties below with a Text and Button object in your UI.
public Text outputText;
public Button startRecoButton;
private object threadLocker = new object();
private bool waitingForReco;
private string message;
private bool micPermissionGranted = false;
#if PLATFORM_ANDROID || PLATFORM_IOS
// Required to manifest microphone permission, cf.
// https://docs.unity3d.com/Manual/android-manifest.html
private Microphone mic;
#endif
public async void ButtonClick()
{
// Creates an instance of a speech config with specified subscription key and service region.
// Replace with your own subscription key and service region (e.g., "westus").
var config = SpeechConfig.FromSubscription("yourSubscriptionKey", "yourRegion");
// Make sure to dispose the recognizer after use!
using (var recognizer = new SpeechRecognizer(config))
{
lock (threadLocker)
{
waitingForReco = true;
}
// Starts speech recognition, and returns after a single utterance is recognized. The end of a
// single utterance is determined by listening for silence at the end or until a maximum of 15
// seconds of audio is processed. The task returns the recognition text as result.
// Note: Since RecognizeOnceAsync() returns only a single utterance, it is suitable only for single
// shot recognition like command or query.
// For long-running multi-utterance recognition, use StartContinuousRecognitionAsync() instead.
var result = await recognizer.RecognizeOnceAsync().ConfigureAwait(false);
// Checks result.
string newMessage = string.Empty;
if (result.Reason == ResultReason.RecognizedSpeech)
{
newMessage = result.Text;
}
else if (result.Reason == ResultReason.NoMatch)
{
newMessage = "NOMATCH: Speech could not be recognized.";
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = CancellationDetails.FromResult(result);
newMessage = $"CANCELED: Reason={cancellation.Reason} ErrorDetails={cancellation.ErrorDetails}";
}
lock (threadLocker)
{
message = newMessage;
waitingForReco = false;
}
}
}
void Start()
{
if (outputText == null)
{
UnityEngine.Debug.LogError("outputText property is null! Assign a UI Text element to it.");
}
else if (startRecoButton == null)
{
message = "startRecoButton property is null! Assign a UI Button to it.";
UnityEngine.Debug.LogError(message);
}
else
{
// Continue with normal initialization, Text and Button objects are present.
#if PLATFORM_ANDROID
// Request to use the microphone, cf.
// https://docs.unity3d.com/Manual/android-RequestingPermissions.html
message = "Waiting for mic permission";
if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
{
Permission.RequestUserPermission(Permission.Microphone);
}
#elif PLATFORM_IOS
if (!Application.HasUserAuthorization(UserAuthorization.Microphone))
{
Application.RequestUserAuthorization(UserAuthorization.Microphone);
}
#else
micPermissionGranted = true;
message = "Click button to recognize speech";
#endif
startRecoButton.onClick.AddListener(ButtonClick);
}
}
void Update()
{
#if PLATFORM_ANDROID
if (!micPermissionGranted && Permission.HasUserAuthorizedPermission(Permission.Microphone))
{
micPermissionGranted = true;
message = "Click button to recognize speech";
}
#elif PLATFORM_IOS
if (!micPermissionGranted && Application.HasUserAuthorization(UserAuthorization.Microphone))
{
micPermissionGranted = true;
message = "Click button to recognize speech";
}
#endif
lock (threadLocker)
{
if (startRecoButton != null)
{
startRecoButton.interactable = !waitingForReco && micPermissionGranted;
}
if (outputText != null)
{
outputText.text = message;
}
}
}
}
The sample code you pasted above still has the placeholder values for region and subscription key. Just double checking that you did in fact replace those strings with your own subscription key and region? If that's true, can you please turn on logging, run the code again, and then provide the log? We can help diagnose from there...
To turn on logging, see https://aka.ms/speech/logging.

I am looking to integrate a gmail widget

This is for a internal portal , and I am looking for a widget that allows user to login to their gmail account and view their account. I tried the Google gadget but it shows the following error
"this is a builtin module, so the UserPrefs and Content are ignored."
also since gadgets are gonna be discontinued I am uncomfortable using that as a long term solution.
Even widget from widgetbox, netvibes etc. don't seem to be working.
Is it because there has been some policy change by Google preventing these widgets from working ? or am i doing something wrong.
I also tried to use the Google widgets in a my site, but unfortunalitly it doesn't work.
It gives the Content are ignored.
No widgets haven't work for my code.
I think there is a policy change in it. But i didn't have any clew about it.
When you say 'login to their account' and what you want to do. You can use OAuth where a user grants your application permission to access their account.
Google have their own library written in a number of languages - some examples using Java, Python and PHP can be found here: https://developers.google.com/google-apps/gmail/xoauth2_libraries
When you use OAuth you register with Google and they give you a ConsumerKey and ConsumerSecret - this is what identifies you application to Google.
Once you do that provide a link to allow them to login - this will take them to a Google login, they login with their account - then they grant permission.
I've had problems using OAuth with GMail but successfully managed it with say their Contacts. For example this is the code I am using to retrieve all a users contacts
public List<Person> GetContacts()
{
OAuthParameters parameters = null;
GOAuthRequestFactory requestFactory = null;
ContactsService service = null;
ContactsQuery feedQuery = null;
ContactsFeed feed = null;
List<Person> contacts = null;
try
{
if (ConsumerKey == String.Empty) throw new ValueIsEmptyOrNullException("ConsumerKey");
if (ConsumerSecret == String.Empty) throw new ValueIsEmptyOrNullException("ConsumerSecret");
if (OAuthCallback == String.Empty) throw new ValueIsEmptyOrNullException("OAuthCallback");
if (SignatureMethod == String.Empty) throw new ValueIsEmptyOrNullException("SignatureMethod");
if (ApplicationName == String.Empty) throw new ValueIsEmptyOrNullException("ApplicationName");
if (Token == String.Empty) throw new ValueIsEmptyOrNullException("Token");
if (Nonce == String.Empty) throw new ValueIsEmptyOrNullException("Nonce");
if (Verifier == String.Empty) throw new ValueIsEmptyOrNullException("Verifier");
if (Scope == String.Empty)
Scope = "https://www.google.com/m8/feeds";
parameters = new OAuthParameters();
parameters.ConsumerKey = ConsumerKey;
parameters.ConsumerSecret = ConsumerSecret;
parameters.Scope = Scope;
parameters.Callback = OAuthCallback;
parameters.SignatureMethod = SignatureMethod;
parameters.Timestamp = Toolbox.GenerateTimeStamp();
parameters.Token = Token;
parameters.TokenSecret = TokenSecret;
parameters.Nonce = Nonce;
parameters.Verifier = Verifier;
requestFactory = new GOAuthRequestFactory("c1", ApplicationName, parameters);
service = new ContactsService(ApplicationName);
service.RequestFactory = requestFactory;
feedQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
feed = service.Query(feedQuery);
if (feed.Entries.Count > 0)
{
contacts = new List<Person>();
foreach (ContactEntry contact in feed.Entries)
{
try
{
if (contact.Name != null)
{
Person person = new Person();
int idStart = contact.Id.Uri.ToString().LastIndexOf('/');
if (idStart > 0)
{
person.PersonId = contact.Id.Uri.ToString().Substring(contact.Id.Uri.ToString().LastIndexOf('/') + 1);
}
else
{
person.PersonId = contact.Id.Uri.ToString();
}
person.GivenName = contact.Name.GivenName;
person.Surname = contact.Name.FamilyName;
person.Birthday = contact.Birthday;
person.Initials = contact.Initials;
person.Location = contact.Location;
person.MaidenName = contact.MaidenName;
person.Occupation = contact.Occupation;
person.Photograph = contact.PhotoUri.ToString();
person.Surname = contact.Name.FamilyName;
if (contact.Emails.Count > 0)
person.Email = contact.Emails[0].Address;
contacts.Add(person);
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return contacts;
}

Outlook : Conflict while saving contact

I am working on a project involving contact synchronization between Outlook and SharePoint. Though there is an out of the box solution provided for this by Microsoft, but it does not cater some specific requirements like custom column synchronization.
For this requirement we had to create an outlook add-in. This add-in handles ItemAdd and ItemChange event for the contact folder created as a result of the synchronization.
In the ItemChange event I check a flag in the Notes field and identify whether the change has been made from SharePoint or Outlook and accordingly update the contact item.
Here is the code for my ItemChange event.
void Items_ItemChange(object Item)
{
try
{
ContactItem ctItem = Item as Outlook.ContactItem;
string customFieldsAndFlag = ctItem.Body;
Dictionary<string, string> customColumnValueMapping = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(customFieldsAndFlag))
{
string[] flagAndFields = customFieldsAndFlag.Split(';');
if (flagAndFields.Length == 2)
{
//SharePoint to Outlook
if (flagAndFields[0] == "1")
{
foreach (string customColumnAndValue in flagAndFields[1].Split('|'))
{
string[] KeyAndValue = customColumnAndValue.Split('=');
if (KeyAndValue.Length == 2)
{
if (ctItem.UserProperties[KeyAndValue[0]] == null)
{
ctItem.UserProperties.Add(KeyAndValue[0], OlUserPropertyType.olText, true, OlUserPropertyType.olText);
ctItem.UserProperties[KeyAndValue[0]].Value = KeyAndValue[1];
}
else
{
ctItem.UserProperties[KeyAndValue[0]].Value = KeyAndValue[1];
}
}
}
ctItem.Body = "2;" + flagAndFields[1];
}
//Outlook to SharePoint
else
{
foreach (string customColumnAndValue in flagAndFields[1].Split('|'))
{
string[] KeyAndValue = customColumnAndValue.Split('=');
if (KeyAndValue.Length == 2)
{
if (ctItem.UserProperties[KeyAndValue[0]] != null && ctItem.UserProperties[KeyAndValue[0]].Value != null)
{
KeyAndValue[1] = ctItem.UserProperties[KeyAndValue[0]].Value.ToString();
}
customColumnValueMapping.Add(KeyAndValue[0], KeyAndValue[1]);
}
}
string newBody = string.Empty;
foreach (KeyValuePair<string, string> kvp in customColumnValueMapping)
{
newBody += kvp.Key + "=" + kvp.Value + "|";
}
if (newBody == flagAndFields[1])
{
return;
}
else
{
ctItem.Body = "0;" + newBody;
}
}
}
}
ctItem.Save();
}
catch(System.Exception ex)
{
// log the error always
Trace.TraceError("{0}: [class]:{1} [method]:{2}\n[message]:{4}\n[Stack]:\n{5}",
DateTime.Now, // when was the error happened
MethodInfo.GetCurrentMethod().DeclaringType.Name, // the class name
MethodInfo.GetCurrentMethod().Name, // the method name
ex.Message, // the error message
ex.StackTrace // the stack trace information
);
// now display a friendly error to the user
MessageBox.Show("There was an application error, you should save your work and restart Outlook.",
"TraceAndLog",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
Now the issue is, the contact item update works fine from outlook the first time. The contact gets updated properly, the add-in works fine and changes get reflected in SharePoint just fine. But when I try to edit the contact again using outlook, a pop-up comes up saying "Item cannot be changed because it was changed by another user or in another window. Do you want to make a copy in the default folder for the item?" and the oulook add-in stops working thereafter.
Can anyone please suggest a solution for this problem?
I cannot use ctItem.Close() as when I use this function, the synchronization process doesn't work and the changes don't get populated to SharePoint.

File connection+j2me

I want to make the application where I can get all the images no matter whether it is in phone or in external memory. I want to import all that images in my application. How can it be possible? I came to know that it is possible through file connection. But not getting exact idea.
Get all the file system roots using FileSystemRegistry.listRoots()
Open connection to each root in turn using FileConnection fconn = (FileConnection)Connector.open(root)
List the folder using fconn.list().
For each entry in the list, if it ends with an image extension (file.getName().endsWith(".png") etc), then it's an image.
If the entry is a folder (file.isDirectory() returns true) then use fconn.setFileConnection(folder) to traverse into that directory/
Do the same recursively for all folders in all roots.
Here is a code snippet I once used for my application. It more or less does the same in funkybros steps.
protected void showFiles() {
if (path == null) {
Enumeration e = FileSystemRegistry.listRoots();
path = DATAHEAD; //DATAHEAD = file:///
setTitle(path);
while (e.hasMoreElements()) {
String root = (String) e.nextElement();
append(root, null);
}
myForm.getDisplay().setCurrent(this);
} else {
//this if-else just sets the title of the Listing Form
if (selectedItem != null) {
setTitle(path + selectedItem);
}
else {
setTitle(path);
}
try {
// works when users opens a directory, creates a connection to that directory
if (selectedItem != null) {
fileConncetion = (FileConnection) Connector.open(path + selectedItem, Connector.READ);
} else // works when presses 'Back' to go one level above/up
{
fileConncetion = (FileConnection) Connector.open(path, Connector.READ);
}
// Check if the selected item is a directory
if (fileConncetion.isDirectory()) {
if (selectedItem != null) {
path = path + selectedItem;
selectedItem = null;
}
//gathers the directory elements
Enumeration files = fileConncetion.list();
while (files.hasMoreElements()) {
String file = (String) files.nextElement();
append(file, null);
}
//
myForm.getDisplay().setCurrent(this);
try {
if (fileConncetion != null) {
fileConncetion.close();
fileConncetion = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}//if (fileConncetion.isDirectory())
else {
System.out.println(path);
//if it gets a file then calls the publishToServer() method
myForm.publishToServer();
}

Resources