I have a small VS C# program that modifies some data from an email signature on HTML format that will be used later in Lotus Notes 8.5.3
Each user is able to generate his own .html file filled with his personal data from the common template.
My problem is that now I would like the software to save the .html file on Lotus Notes Data directory and then configure the client to use that specific signature without the user having to go through the menues "More-->Preferences-->Signature" himself.
Here is my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace FirmaCorreo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Generar_Click(object sender, RoutedEventArgs e)
{
string suSaludo;
suSaludo = Texto1.Text;
string suNombre;
suNombre = Texto2.Text;
string suCargo;
suCargo = Texto3.Text;
string suCargo2;
suCargo2 = Texto4.Text;
string suMovil;
suMovil = Texto5.Text;
string suDirecto;
suDirecto = Texto6.Text;
string suDelegacion;
if (DelegacionVillajoyosa.IsChecked == true)
{
suDelegacion = "Villajoyosa";
}
else if (DelegacionCanarias.IsChecked == true)
{
suDelegacion = "Canarias";
}
else if (DelegacionVigo.IsChecked == true)
{
suDelegacion = "Vigo";
}
else
{
suDelegacion = "Francia";
}
var contents = System.IO.File.ReadAllText(#"C:\Users\Public\Documents\IS-IT\FirmaCorreo\Plantilla\Plantillacorreo.html", Encoding.GetEncoding(28591));
contents = contents.Replace("<!--Saludo-->", suSaludo);
contents = contents.Replace("<!--NombreDelEmpleado-->", suNombre);
contents = contents.Replace("<!--CargoDelEmpleado-->", suCargo);
contents = contents.Replace("<!--CargoDelEmpleado2-->", "<br />"+suCargo2);
contents = contents.Replace("<!--TelefonoMovil-->", "Mobile.- "+suMovil);
contents = contents.Replace("<!--TelefonoDirecto-->", "<br />Direct.- "+suDirecto);
contents = contents.Replace("<!--Delegacion"+suDelegacion, "<!-- -->");
System.IO.File.WriteAllText(#"C:\Users\Public\Documents\IS-IT\FirmaCorreo\Plantilla\PlantillacorreoModificada.html", contents, Encoding.GetEncoding(28591));
}
}
}
On my Lotus Notes 8.5.3 installation I see a notes.ini file which seems to have the signature configuration:
...
$SigSet=1
$SigState=1
$SigSetValue=1
....
$tmpStrFilter=HTML File
$tmpSigPath=C:\Lotus\Notes\Data\FirmaCorreo\FirmaPedro.html
...
Notes allows three different options for mail signatures:
I thought maybe I just had to edit notes.ini on each client to set up the resulting HTML file from my program.
The problem is notes.ini doesn't change when I change the type of signature on my client.
Is there any way to get the resulting HTML file to be the default signature on Lotus Notes without asking each user to go to the Preferences menu and select the right settings?
Can I have my C# program do that for them?
The html file path is stored in a profile document in the Mail database called $CalendarProfile and the field Signature2
You might be able hook into Notes using Microsoft COM objects(windows) and read the document, but then the code need to run on the client machine using the users password.
Another approach can be to create a lotusscript that updates the profile when user open the mailfile for the first time, this can be done once by changing the mail template and pushing it out to all users.
Keep in mind that a signature referenced to local disk will not work in webmail
Related
Im having an issue with using DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open is not opening a spreadsheet, it returns a file not found exception. The class i'm using has worked many times before, but i've never used it in a UWP project.
I've created a simple example and found that I get the same issue when using File.Exists i've include all the using statements i use if that helps.
Does anyone know why the File.Exists cannot detect the file?
and yes i've triple checked the file does exist on D:!
C# UWP Project created using UWP Template Studio [MainPage.xaml.cs]
using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using UWP_APP.ViewModels;
using Windows.UI.Xaml.Controls;
namespace UWP_APP.Views
{
public sealed partial class MainPage : Page
{
public MainViewModel ViewModel { get; } = new MainViewModel();
public MainPage()
{
InitializeComponent();
string filePath = #"D:\example.xlsm";
if (File.Exists(filePath))
{
int a = 1;
}
else
{
int a = 0;
}
}
Does anyone know why the File.Exists cannot detect the file?
UWP app is running in sandbox, because File.Exists is System.IO api. So it could not work for accessing file except ApplicationData.Current.LocalFolder. If you do want to check if the file exist in the specific path, we suggest you add broadFileSystemAccess capability and enable in the system file access setting. This capability works for APIs in the Windows.Storage namespace.
And using the flolowing method to check if the file exist.
try
{
var file = StorageFile.GetFileFromPathAsync(#"C:\Users\Karan\OneDrive\Desktop\2010.pdf");
if (file != null)
{
isExist = true;
}
}
catch (Exception)
{
isExist = false;
}
I am trying to develop C# Google Vision API function.
the code is supposed to compile into dll and it should run to do the following steps.
get the image from the image Path.
send the image to Google vision api
Call the document text detection function
get the return value (text string values)
Done
When I run the dll, However, it keeps giving me an throw exception error. I am assuming that the problem is on the google credential but not sure...
Could somebody help me out with this? I don't even know that the var credential = GoogleCredential.FromFile(Credential_Path); would be the right way to call the json file...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
var credential = GoogleCredential.FromFile(Credential_Path);
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
You just need to setup the environment variable GOOGLE_APPLICATION_CREDENTIALS as mentioned here
You mus have to mention you json file name in the environment variable as this.
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
Your code would look like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
//var credential = GoogleCredential.FromFile(Credential_Path);
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
or you can send it through your Credential_Path variable.
for more details please visit Google Vision API Docs
You need to setup your environment in your console with code like this :
Windows Server:
$env:GOOGLE_APPLICATION_CREDENTIALS="File Path"
Linux Server :
export GOOGLE_APPLICATION_CREDENTIALS="File Path"
Hope it helps!
Need to integrate this PowerShell script into my C# Assembly code. No idea how to do this. If any other information is needed please do not hesitate to ask. Thanks in advance.
PowerShell Script:
#Script that does the linking and renaming:
# Creates a variable called IncidentID and points Incident # to it for use within the script
Param(
[string]$IncidentID
)
# Load the SMlets module
Import-Module SMlets
# Get the Incident Class
$IncClass = Get-SCSMClass -Name System.WorkItem.Incident$
# Get the RMA Class
$RMAClass = Get-SCSMClass -Name COMPANY.RMA.Class
# Build the Filter String
$FilterStr = "ID -eq " + $IncidentID
# Find the Incident we need to link to an RMA
$Inc = Get-SCSMObject -Class $IncClass -Filter $FilterStr
$RMAIncText = "[Linked to Incident " + $Inc.ID + "]"
$RMADescription = $RMAIncText
New-SCSMObject -Class $RMAClass -PropertyHashtable (#{Title = $Inc.Title; Description = $RMADescription})
# Find the new RMA to be linked
$FilterStr = "Description -eq '$RMADescription'"
$RMA = Get-SCSMObject -Class $RMAClass -Filter $FilterStr
#Set RMA Number Variable
$RMANumber = $RMA.RMA_ID;
#Clean up DisplayName, Title and Description
$RMA | Set-SCSMObject -PropertyHashtable #{"DisplayName" = $RMANumber; "Title" = $RMANumber; "Description" = $RMANumber;}
## Create an Incident Related Items instance referencing the new RMA
$RWIClass = Get-SCSMRelationshipClass -Name System.WorkItemRelatesToWorkItem$
New-SCSMRelationshipObject -Relationship $RWIClass -Source $Inc -Target $RMA -Bulk
# Unload the SMlets module
Remove-Module SMlets
Assembly Code:
public class RMATask : ConsoleCommand
{
public RMATask()
{
}
public override void ExecuteCommand(IList<NavigationModelNodeBase> nodes, NavigationModelNodeTask task, ICollection<string> parameters)
{
IManagementGroupSession session = (IManagementGroupSession)FrameworkServices.GetService<IManagementGroupSession>();
EnterpriseManagementGroup emg = session.ManagementGroup;
ManagementPack mp = emg.ManagementPacks.GetManagementPack(new Guid("a82d62c5-ece0-35fd-a266-9afa246dea78"));
ManagementPackClass mpc = emg.EntityTypes.GetClass(new Guid("4b081ab1-f48e-9c62-77bc-76bc31349030"));
ManagementPackObjectTemplate mpt = emg.Templates.GetObjectTemplate(new Guid("92ed7c4d-aff5-819e-90f8-c92064c50cd6"));
NavigationModelNodeBase nodeIn = nodes[0];
NavigationModelNodeBase nmnbNew;
NavigationModelNodeTask nmntNew = NavigationTasksHelper.CreateNewInstanceLink(mpc, mpt);
Microsoft.EnterpriseManagement.GenericForm.GenericCommon.MonitorCreatedForm(nodeIn, nmntNew, out nmnbNew);
}
}
For those interested in the details here they are:
Problem
Basically, we have help desk analysts who generate the incidents. SOMETIMES, they may have a need to generate an RMA (Return Merchandise Authorization, if you don't know what that means, just know that it is another form they need to fill out), and that RMA needs to be associated with an incident. An incident does not REQUIRE to have an RMA, but every RMA needs to be attached to its appropriate parent incident.
To do this I created a new class called COMPANY.RMA.Class, created a new form from scratch in Visual Studio, and packaged the MP (Management Pack) XML and form assembly (.dll) into an MPB (management pack bundle).
I uploaded this to the console, and created a new console task called "Create RMA" that became visible when selecting the incident module.
This task would launch my PowerShell script, which in turn would take the ID of the incident selected or opened, create an RMA object, and associate the RMA object created with the ID # of the Incident (allowing it to be seen later in the "Related Items" Tab of the incident).
However, I ran into a problem here. I create the linking functionality correctly, but I cannot get the RMA form to automatically open up after it is created. Instead, when the task is run, it creates the object and saves it, but the analyst has to close the incident and reopen it to refresh the new data, navigate to the "Related Items" tab, and select the newly created RMA to open it up and fill out the form. This is alot of extra work and should be eliminated.
The correct functionality should be to create the RMA form, associate it with the open/selected incident, and launch the RMA form it just created to allow the analyst to fill in its details.
Apparently there is no function to call/launch the form directly from the console task. It seems I must modify the assembly code directly to be able to access the SCSM SDK (the layer I need to be working in). This is where I am lost - I have no idea how to convert my PowerShell script to C# Assembly code. Any help would be greatly appreciated.
You may use the PowerShell class to host PowerShell in your app.
The host application can define the runspace where commands are run, open sessions on a local or remote computer, and invoke the commands either synchronously or asynchronously based on the needs of the application.
There's guidance here.
I ended up solving this alternatively.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// using System.Threading.Tasks; <- .NET 4.5 only
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.ConnectorFramework;
// using Microsoft.EnterpriseManagement.UI.Core;
using Microsoft.EnterpriseManagement.UI.Extensions.Shared;
using Microsoft.EnterpriseManagement.UI.FormsInfra;
using Microsoft.EnterpriseManagement.UI.Core.Connection;
using Microsoft.EnterpriseManagement.UI.DataModel;
using Microsoft.EnterpriseManagement.UI.SdkDataAccess;
using Microsoft.EnterpriseManagement.UI.SdkDataAccess.DataAdapters;
using Microsoft.EnterpriseManagement.UI.WpfWizardFramework;
using Microsoft.EnterpriseManagement.ServiceManager.Application.Common;
using Microsoft.EnterpriseManagement.ConsoleFramework;
using Microsoft.EnterpriseManagement.GenericForm;
// using System.Management.Automation;
[assembly: CLSCompliant(true)]
namespace COMPANY.RMA
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
class RMATask : CreateWithLinkHandler
{
public RMATask()
{
try
{
// Sealed Class GUID
this.createClassGuid = new Guid("9ebd95da-1b16-b9ea-274d-6b0c16ce1bf3");
this.classToDelegate = new Dictionary<Guid, CreateLinkHelperCallback>()
{
{ ApplicationConstants.WorkItemTypeId, new CreateLinkHelperCallback (this.WorkItemCallback) }
};
}
catch (Exception exc1)
{
MessageBox.Show(exc1.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public void WorkItemCallback(IDataItem RMAForm, IDataItem IncidentForm)
{
try
{
// Note to self: RelatedWorkItems should be in MP XML as alias under TypeProjections
if (RMAForm != null && RMAForm.HasProperty("RelatedWorkItems"))
{
// Perform Linking
RMAForm["RelatedWorkItems"] = IncidentForm;
// Copy Incident Title to RMA Title
RMAForm["Title"] = IncidentForm["Title"];
// Copy Incident Description to RMA Description
RMAForm["Description"] = IncidentForm["Description"];
}
}
catch (Exception exc2)
{
MessageBox.Show(exc2.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
Im trying to get my notefunction to post the current city you are in by using your gps coordinates when saving a note. Right now it's only showing "unknown location". Im kinda lost right now and i have worked so long with this code to try and get it to work so please could anyone tell me what i have done wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using Secret.myTerraService;
namespace Secret
{
public partial class AddNotePage : PhoneApplicationPage
{
private IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
private string location = "";
#region Hämtar din geografiska position
public AddNotePage()
{
InitializeComponent();
GeoCoordinateWatcher watcher;
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
{
MovementThreshold = 20
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
// location is unsupported on this device
break;
case GeoPositionStatus.NoData:
// data unavailable
break;
}
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
var epl = e.Position.Location;
// Access the position information thusly:
epl.Latitude.ToString("0.000");
epl.Longitude.ToString("0.000");
epl.Altitude.ToString();
epl.HorizontalAccuracy.ToString();
epl.VerticalAccuracy.ToString();
epl.Course.ToString();
epl.Speed.ToString();
e.Position.Timestamp.LocalDateTime.ToString();
}
void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e)
{
location = e.Result;
//throw new NotImplementedException();
}
#endregion
#region Knappfunktioner
private void AppBar_Cancel_Click(object sender, EventArgs e)
{
navigateBack();
}
private void AppBar_Save_Click(object sender, EventArgs e)
{ // spara en ny anteckning
if (location.Trim().Length == 0)
{
location = "Okänd Plats";
}
// skapa namnet på filen
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.Year);
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Month));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Day));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Hour));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Minute));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Second));
sb.Append("_");
location = location.Replace(" ", "-");
location = location.Replace(", ", "_");
sb.Append(location);
sb.Append(".txt");
//spara filen i Isolated Storage
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
try
{
using (var fileStream = appStorage.OpenFile(sb.ToString(), System.IO.FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.WriteLine(editTextBox.Text);
}
}
}
catch
{
// åtgärda vid senare tillfälle..
}
//Klart Navigera tillbaka till NoteMainPage
navigateBack();
}
When testing this, I can see a few points where your code could break. You should debug with breakpoints to actually confirm that your app is getting GPS location data. If not, use the Windows Phone emulator and run a GPS simulation (and then confirm again).
Next, once you know that your GPS data is coming in and formatted correctly for your Terra Web Service, confirm that the data is actually being sent to the Terra Web Service and that data is being returned from the web service call. If your Terra Web Service is returning "Unknown Location" still, try again but this time plot the GPS location near a major city to increase the odds of the web service knowing what city you are close to. If you are still returning "Unknown Location" then you can be fairly certain that the issue resides with the web service provider.
In my experience with the Windows Phone location services (I've only used dev phones with WiFi access (i.e. no sim)), location data sometimes takes a few seconds or minutes to pickup. If you're testing this on a physical dev phone in a basement or an area with limited access for the GPS to find you, odds are the data isn't being generated. Also, because the Windows Phone location data isn't necessarily instant, you can't always call it on the fly and expect it to have location data ready. In my experience I have had the user opt in to location services (per the Windows Phone Marketplace submission requirements) and then have a background agent pull location data while the user is using the app. That way location data is likely to be ready by the time user would need it (like your example when the user saves the note).
Here's a working example I made for you in C# that will work for your Windows Phone app. The sample is a console app for the sake of simplicity and time. If you can't figure it out still, I'll code it up for Windows Phone. With this though you really have everything you need to make it work, just plug in the lat and long variables. Download Working Source Code (Visual Studio 2010)
C# Source code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TerraServiceExample.com.msrmaps; // add the service using statement
// http://msrmaps.com/terraservice2.asmx
namespace TerraServiceExample
{
class Program
{
/// <summary> The main entry point for the application. </summary>
static void Main(string[] args)
{
// Create the GPS point from your location services data
LonLatPt location = new LonLatPt();
// Modify Lat and Lon based on your needs
// This example uses the GPS Coordinates for "Eau Claire, Wisconsin, United States"
location.Lat = 44.811349;
location.Lon = -91.498494;
// Create a new TerraService object
TerraService ts = new TerraService();
// Output the nearest location from the TerraService
Console.WriteLine(ts.ConvertLonLatPtToNearestPlace(location));
// For console app to stay open/close easily
Console.WriteLine("Press any key to close window...");
Console.ReadKey();
// Lastly, appreciate the Microsoft folks that made this available for free
// They are all interesting individuals but you should read about Jim Gray via Wikipedia to
// understand some history behind this cool web service.
}
}
}
I am currently working on batch processing application using MSMQ in C#. In the application design, I have an error queue containing XML messages using the ActiveXFormatter. I know that I can write an application to write these error messages to text files or database tables.
Are there other pre-built tools available allowing you to export messages to variety of formats (i.e. text files, database tables, etc.)? I am just looking for best practices.
Ok. I found the solution of writing code to be really easy. Here's my reference solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
namespace ExportMSMQMessagesToFiles
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnExportTextFiles_Click(object sender, EventArgs e)
{
//Setup MSMQ using path from user...
MessageQueue q = new MessageQueue(txtMSMQ.Text);
//Setup formatter... Whatever you want!?
q.Formatter = new ActiveXMessageFormatter();
// Loop over all messages and write them to a file... (in this case XML)
MessageEnumerator msgEnum = q.GetMessageEnumerator2();
int k = 0;
while (msgEnum.MoveNext())
{
System.Messaging.Message msg = msgEnum.Current;
string fileName = this.txtFileLocation.Text + "\\" + k + ".xml";
System.IO.File.WriteAllText(fileName, msg.Body.ToString());
k++;
}
MessageBox.Show("All done!");
}
}
}