How do I get the display name of the user that is logged in? Not the username, but the display name, such as is shown in the screenshot below - and as seen on the start menu in any Windows Vista/7 computer.
I tried a bunch of different suggestions from other questions, but they all show the username, not the display name. You can see the results of these attempts in the above screenshot.
Imports System.Security.Principal
Imports System.Threading
Imports System.IO
Imports System
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MsgBox("1: " & System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString & vbCrLf & _
"2: " & Environment.UserDomainName & vbCrLf & _
"3: " & WindowsIdentity.GetCurrent().Name & vbCrLf & _
"4: " & Thread.CurrentPrincipal.Identity.Name & vbCrLf & _
"5: " & Environment.UserName & vbCrLf & _
"6: " & My.User.Name & vbCrLf &
"7: " & My.Computer.Name)
End Sub
End Class
You should use UserPrincipal.DisplayName:
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
To do so, you'll need to and add a reference to System.DirectoryServices.AccountManagement.dll from your project.
Note: Doesn't work when machine is unplugged from the network or domain server is not reachable.
Try this
http://msdn.microsoft.com/en-us/library/sfs49sw0(v=vs.110).aspx
using System.IO;
using System;
using System.Security.Principal;
class Program
{
static void Main()
{
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
}
}
This is contained within the System.DirectoryServices namespace so you need to add this in the using section.
Then you can use System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName which returns the Display Name. This is typically shown in the Start Menu.
Related
We are currently developing an addin that interact with the end user visually to give some informations, and we wanted to use Mailtips but apparently it is not possible from what we saw
Nevertheless, is it possible to have something similar or to mimic this kind of tip (2nd sshot would be ideal)..
Option 1:
https://i.stack.imgur.com/vcQYb.png
Option 2:
https://i.stack.imgur.com/7k19w.png
We also looked and form region but that would be the last option, ideal would be to have the tooltip in 2nd screenshot to display a small message to help user (any clue appreciated).
We were also looking for a function to disable links in the body (as the junk filter does), but also no chance finding this through the documentation (maybe internal procedure)
Looking everywhere for documented elements...
On the screenshot you have seen a standard Outlook notification and MailTips - that is a feature of Exchange, not Outlook.
We also looked and form region but that would be the last option, ideal would be to have the tooltip in 2nd screenshot to display a small message to help user (any clue appreciated).
The Outlook object model doesn't provide anything for that, there is no built-in property or method for that. The only possible option is to use a form region where you could put your custom UI at the bottom of the standard form/window in Outlook. The Adjoining layout available for Outlook form regions appends the form region to the bottom of an Outlook form's default page. So, if you want to place the form at the top you need to use Windows API functions to subclass Outlook windows or consider using the Advanced Outlook view and form regions where the top layout is provided out of the box.
Also you may consider developing a web add-in for Outlook where you could set up notification items programmatically from the add-in, see Office.NotificationMessages interface for more information. For example:
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/35-notifications/add-getall-remove.yaml
const id = $("#notificationId").val();
const details =
{
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Non-persistent informational notification message with id = " + id,
icon: "icon1",
persistent: false
};
Office.context.mailbox.item.notificationMessages.addAsync(id, details, handleResult);
See Build your first Outlook add-in to get started quickly on that.
We were also looking for a function to disable links in the body (as the junk filter does), but also no chance finding this through the documentation (maybe internal procedure)
You need to process the message body on your own. The Outlook object model doesn't provide any property or method for that out of the box.
The Outlook object model supports three main ways of customizing the message body:
The Body property returns or sets a string representing the clear-text body of the Outlook item.
The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately.
The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.
You can add a special MAPI property (used by Web addins, DASL name "http://schemas.microsoft.com/mapi/string/{A98A1EF9-FF40-470B-A0D7-4D7DCE6A6462}/WebExtNotifications") to show the notification banner.
Something along the following lines (VBA, you'd need to deselect and select again the currently selected message to see the change):
notificationXml = "<?xml version=""1.0""?>" & vbCrLf & _
"<Apps>"& vbCrLf & _
" <App id=""00000000-0000-0000-0000-000000000000"">"& vbCrLf & _
" <Notifications>"& vbCrLf & _
" <Notification key=""notification"">"& vbCrLf & _
" <type>0</type>"& vbCrLf & _
" <message>Test notification
with two lines</message>"& vbCrLf & _
" </Notification>"& vbCrLf & _
" </Notifications>"& vbCrLf & _
" </App>"& vbCrLf & _
" <App id=""00000000-0000-0000-0000-000000000001"">"& vbCrLf & _
" <Notifications>"& vbCrLf & _
" <Notification key=""notification"">"& vbCrLf & _
" <type>0</type>"& vbCrLf & _
" <message>Another notification</message>"& vbCrLf & _
" </Notification>"& vbCrLf & _
" </Notifications>"& vbCrLf & _
" </App>"& vbCrLf & _
"</Apps>"
set msg = Application.ActiveExplorer.Selection(1)
msg.PropertyAccessor.SetProperty "http://schemas.microsoft.com/mapi/string/{A98A1EF9-FF40-470B-A0D7-4D7DCE6A6462}/WebExtNotifications", notificationXml
msg.Save
I have looked through the code but I simply do not have the understanding to know what functions are doing what and how in relation to C# my primary coding language.
Set mSkype = WScript.CreateObject("Skype4COM.Skype", "Skype_")
ContactName=InputBox ("Enter the contact's Skype User Name" & CHR(13) & "Note that this must be the User Name and not the Display Name", "User Name:")
If ContactName = "" Then
WScript.Quit
Else
If mSkype.User(ContactName).FullName="" then
WScript.Echo ("The name " & ContactName & " is not in your Contact List")
WScript.Quit
End If
End If
PictureFileName=InputBox ("Enter the path and name of the Picture" & CHR(13) & "The file extension must be .jpg", "Save Picture as:")
If PictureFileName="" Then
WScript.Quit
End If
cmdStr = "GET USER" & " " & ContactName & " " & "AVATAR 1" & " " & PictureFileName
mSkype.SendCommand mSkype.Command(0, cmdStr)
Oh and I do have skype4com imported and im using that api, that is not the issue with conversion.
InputBox is a window that displays that prompts for input. It is available in VB.NET, and you can actually use it in C# by adding a reference to Microsoft.VisualBasic. See here.
WScript is also not available in VB and it would probably be good to research how to use the Skype plugin in the Skype Developer Forum. Here's a link about how to use the Skype DLL in C#.
I have added global error handling into my application to catch-all unhandled exceptions. I now just added the functionality to add the bug automatically to my fogbugz account. Now here is my issue.
I added a reference to the dll and also had to add the import declaration for the library. After doing this the code shows no errors. Although as soon as I go to debug the code or build it I get this error:
'BugReport' is not declared. It may be inaccessible due to its protection level.
I am geussing it has to do with some kind of protection? This catch all is in my applicationevents.vb class.
I have tried the same code in another project and it works without error so I know it is not the code. I just don't know what it is? Do I have to change something in my application settings? Here is the code anyways. I replaced the strings with my information for privacy.
Imports FogBugz
Namespace My
' The following events are available for MyApplication:
'
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(ByVal _
sender As Object, ByVal e As _
Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) _
Handles Me.UnhandledException
'TO DO: SET THESE VALUES BEFORE CALLING THIS METHOD!
Dim url As String = "StackOverFlowDemoString"
'example: http://localhost/fogbugz/scoutSubmit.asp
Dim user As String = "StackOverFlowDemoString"
'existing FogBugz User
Dim project As String = "StackOverFlowDemoString"
'existing FogBugz project
Dim area As String = "StackOverFlowDemoString"
'existing FogBugz area
Dim email As String = "StackOverFlowDemoString"
'email address of the customer who reports the bug
Dim defaultMessage As String = "Bug has been submitted. Every bug submitted helps us make this software that much better. We really do appreciate it."
'the message to return to the user if no Scout Message is found for an existing duplicate bug
Dim forceNewBug As Boolean = False
'If set to true, this forces FogBugz to create a new case for this bug, even if a bug with the same description already exists.
'************************************************************************************
'send the bug we created:
BugReport.Submit(url, user, project, area, email, forceNewBug, _
defaultMessage, e.Exception, True, "{0}.{1}.{2}.{3}", True)
' If the user clicks No, then exit.
e.ExitApplication = _
MessageBox.Show(e.Exception.Message & _
vbCrLf & "Oops! It looks like we have encountered a bug. A bug report has been sent to the developers, so they can have it fixed in a jiffy. Continue?", "An Error has occured.", _
MessageBoxButtons.YesNo, _
MessageBoxIcon.Question) _
= DialogResult.No
End Sub
End Class
End Namespace
The "protection level" refers to the access modifier on your BugReport class.
If you declare a class as Friend (Internal in C#), it is accessible to other classes in the same assembly (.dll).
When you attempt to reference that class from another project, it is not accessible.
You need to change Friend to Public.
I have a 3G card to provide internet to a remote computer... I have to run a program(provided with the card) to establish the connection... since connections suddenly is lost I wrote a script that Kills the program and reopens it so that the connection is reestablished, there are certain versions of this program that don't kill the connection when killed/terminated, just when closed properly.
so I am looking for a script or program that "Properly Closes" a window so I can close it and reopen it in case the connection is lost.
this is the code that kills the program
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill
strComputer = "."
strProcessKill = "'Telcel3G.exe'"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
objProcess.Terminate()
Next
WSCript.Echo "Just killed process " & strProcessKill _
& " on " & strComputer
WScript.Quit
If you have to use VBScript, one easy way would be to activate the app and then use SendKeys to restore it if it's minimized and send it "alt-f4". It's hacky, but it may be easier than finding the main window's handle, and it might work well enough for you.
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill
strComputer = "."
strProcessKill = "'Telcel3G.exe'"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
dim WshShell
set WshShell = CreateObject("WScript.Shell")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
WshShell.AppActivate objProcess.ProcessId
WScript.Sleep 1000
WshShell.Sendkeys "% r"
WScript.Sleep 1000
WshShell.Sendkeys "%{F4}"
Next
As I understand it, the basic idea is to shut the process down cleanly, as opposed to abruptly terminating it. One way would be to post a Windows message to the main window with WM_CLOSE.
(You might be able to simulate this by sending keystrokes corresponding to Alt+F4, but it's best to just send WM_CLOSE.)
After migrating my Visual Studio 2003 projects to VS2005 (or VS2008) my forms would still be inside a single file.
New forms on VS2005 and VS2008 are created using partial classes where all code generated by the editor is kept in the Designer.cs file.
Since the VS2005 form creates is a much better way of dealing with forms, I would like to know if there is a way of converting all my old single-file forms to the VS2005 partial class method.
I've done some by hand but this is very tricky and can lead to some serious errors.
Any suggestions? PS: I'm using Microsoft Visual C# 2008 Express Edition.
This seem to be what you want.
Converting Visual Studio 2003 WinForms to Visual Studio 2005/2008 partial classes :
NET 2.0 introduced partial classes which enables “.designer” files in
Visual Studio 2005 and later. That is, all of the visual
designer-generated code (control declarations, the InitializeComponent
method, etc) can be kept in a file separate from your regular code.
When you open up a .NET 1.x Visual Studio 2003 WinForms project up in
Visual Studio 2005/2008 it will upgrade your project to .NET 2.0 just
fine, but unfortunately it doesn’t migrate your WinForms classes over
to the new “.designer” project structure.
Initially I thought this
would be a job for a DXCore plug-in (the free framework upon which
CodeRush is built) as it provides plug-ins with an object model of the
code which could be used to grab all the right members and move them
over into a designer file. Before I looked into this though I checked
what the options were for simply implementing it as a Visual Studio
Macro. I was fully expecting to have to use a regular expression to
grep the code file to perform the task, but was pleasantly surprised
to find that the Visual Studio extensibility API in available to
macros provides a code model (based on the .NET CodeDom I presume)
which you can traverse to inspect and manipulate the underlying code.
So, here’s what the resulting “ExtractWinFormsDesignerFile” macro
does:
Locates the first class in the selected project item (DTE.SelectedItems.Item(1).ProjectItem) by traversing the
ProjectItem.FileCodeModel.CodeElements
Extracts the InitializeComponent and Dispose methods from the class by traversing CodeClass.Members
Extracts all control fields: that is, all fields whose type derives from System.Windows.Forms.Control or System.ComponentModel.Container
or whose type name starts with System.Windows.Forms
Puts all the extracted code into a new “FormName.Designer.cs” file.
This is currently C# only – it could easily be converted to
generated VB.NET code or adapted use the FileCodeModel properly and
perhaps create the code in an language-agnostic way when generating
the designer file. I took a shortcut in just generating the designer
file as a string and writing it directly to a file.
To “install”:
download the macro text :
' -------------------------------------------------------------------------
' Extract WinForms Designer File Visual Studio 2005/2008 Macro
' -------------------------------------------------------------------------
' Extracts the InitializeComponent() and Dispose() methods and control
' field delarations from a .NET 1.x VS 2003 project into a VS 2005/8
' style .NET 2.0 partial class in a *.Designer.cs file. (Currently C#
' only)
'
' To use:
' * Copy the methods below into a Visual Studio Macro Module (use
' ALT+F11 to show the Macro editor)
' * Select a Windows Form in the Solution Explorer
' * Run the macro by showing the Macro Explorer (ALT+F8) and double
' clicking the 'ExtractWinFormsDesignerFile' macro.
' * You will then be prompted to manually make the Form class partial:
' i.e. change "public class MyForm : Form"
' to
' "public partial class MyForm : Form"
'
' Duncan Smart, InfoBasis, 2007
' -------------------------------------------------------------------------
Sub ExtractWinFormsDesignerFile()
Dim item As ProjectItem = DTE.SelectedItems.Item(1).ProjectItem
Dim fileName As String = item.FileNames(1)
Dim dir As String = System.IO.Path.GetDirectoryName(fileName)
Dim bareName As String = System.IO.Path.GetFileNameWithoutExtension(fileName)
Dim newItemPath As String = dir & "\" & bareName & ".Designer.cs"
Dim codeClass As CodeClass = findClass(item.FileCodeModel.CodeElements)
Dim namespaceName As String = codeClass.Namespace.FullName
On Error Resume Next ' Forgive me :-)
Dim initComponentText As String = extractMember(codeClass.Members.Item("InitializeComponent"))
Dim disposeText As String = extractMember(codeClass.Members.Item("Dispose"))
Dim fieldDecls As String = extractWinFormsFields(codeClass)
On Error GoTo 0
System.IO.File.WriteAllText(newItemPath, "" _
& "using System;" & vbCrLf _
& "using System.Windows.Forms;" & vbCrLf _
& "using System.Drawing;" & vbCrLf _
& "using System.ComponentModel;" & vbCrLf _
& "using System.Collections;" & vbCrLf _
& "" & vbCrLf _
& "namespace " & namespaceName & vbCrLf _
& "{" & vbCrLf _
& " public partial class " & codeClass.Name & vbCrLf _
& " {" & vbCrLf _
& " #region Windows Form Designer generated code" & vbCrLf _
& " " & fieldDecls & vbCrLf _
& " " & initComponentText & vbCrLf _
& " #endregion" & vbCrLf & vbCrLf _
& " " & disposeText & vbCrLf _
& " }" & vbCrLf _
& "}" & vbCrLf _
)
Dim newProjItem As ProjectItem = item.ProjectItems.AddFromFile(newItemPath)
On Error Resume Next
newProjItem.Open()
DTE.ExecuteCommand("Edit.FormatDocument")
On Error GoTo 0
MsgBox("TODO: change your class from:" + vbCrLf + _
" ""public class " + codeClass.FullName + " : Form""" + vbCrLf + _
"to:" + _
" ""public partial class " + codeClass.FullName + " : Form""")
End Sub
Function findClass(ByVal items As System.Collections.IEnumerable) As CodeClass
For Each codeEl As CodeElement In items
If codeEl.Kind = vsCMElement.vsCMElementClass Then
Return codeEl
ElseIf codeEl.Children.Count > 0 Then
Dim cls As CodeClass = findClass(codeEl.Children)
If cls IsNot Nothing Then
Return findClass(codeEl.Children)
End If
End If
Next
Return Nothing
End Function
Function extractWinFormsFields(ByVal codeClass As CodeClass) As String
Dim fieldsCode As New System.Text.StringBuilder
For Each member As CodeElement In codeClass.Members
If member.Kind = vsCMElement.vsCMElementVariable Then
Dim field As CodeVariable = member
If field.Type.TypeKind <> vsCMTypeRef.vsCMTypeRefArray Then
Dim fieldType As CodeType = field.Type.CodeType
Dim isControl As Boolean = fieldType.Namespace.FullName.StartsWith("System.Windows.Forms") _
OrElse fieldType.IsDerivedFrom("System.Windows.Forms.Control") _
OrElse fieldType.IsDerivedFrom("System.ComponentModel.Container")
If isControl Then
fieldsCode.AppendLine(extractMember(field))
End If
End If
End If
Next
Return fieldsCode.ToString()
End Function
Function extractMember(ByVal memberElement As CodeElement) As String
Dim memberStart As EditPoint = memberElement.GetStartPoint().CreateEditPoint()
Dim memberText As String = String.Empty
memberText += memberStart.GetText(memberElement.GetEndPoint())
memberStart.Delete(memberElement.GetEndPoint())
Return memberText
End Function
and copy the methods into a Visual Studio
Macro Module (use ALT+F11 to show the Macro editor).
To use:
Select a Windows Form in the Solution Explorer
Run the macro by showing the Macro Explorer (ALT+F8) and double-clicking the ‘ExtractWinFormsDesignerFile’ macro. (Obviously
you can hook the macro up to a toolbar button if you like.)
You will then be prompted to manually make the Form class partial (another bit I was too lazy to work out how to get the macro to do):
i.e. change public class MyForm : Form to public partial class
MyForm : Form
As you're probably aware, all the Express editions do not support third party extensions. Unfortunately I know of no stand alone tools that can do what you are asking.
I've experimented with splitting a Winform class into partials classes. As you discovered, it is not a trivial undertaking. This question has been asked before. Unlike Martin's attempt, I went the other direction. Instead of creating a designer file, I renamed the existing file to MyForm.Designer.cs and created a new MyForm.cs file. I then proceeded in a similar manner, moving the "code behind" instead of the designer code into my new class.
The one sticking point with either of these techniques is that future changes to the form still don't generate in the correct class file. This is because the project file still doesn't recognize the two files to be linked together. Your only option is to manually edit the project file in a text editor. Look for the following:
<Compile Include="MyForm.Designer.cs">
<SubType>Form</SubType>
</Compile>
Replace the <SubType>...</SubType> with <DependentUpon>MyForm.cs</DependentUpon> so the end result looks like:
<Compile Include="MyForm.Designer.cs">
<DependentUpon>MyForm.cs</DependentUpon>
</Compile>
Another solution I experimented with was simply creating an new form and dragging the controls from the old form to it. This actually worked to an extent. All the controls migrated along with all their properties. What didn't migrate was event handlers. These you would have to cut and paste from the old form, then go through each control and reselect the appropriate handler from the form designer. Depending on the complexity of the form this might be a reasonable alternative.
From my own personal experiences supporting multiple UIs the best approach is to keep form design simple and separate the business logic from the UI completely. The MVP Passive view works pretty well for this. By delegating as much of the responsibility to a presenter class it becomes trivial to implement the form in a different UI framework. WinForms, WebForms, WPF, etc, it makes little difference to the presenter class. All it sees in an interface exposing a list of properties it manipulates. Of course all the shoulda coulda wouldas in the world won't help when the problem you are facing is here and now.