How can I get the device name? - c#

I'm developing an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS.
I want to get the device name using code lines.
Any one have an idea on this ?
Note : I'm working with VS2008 using C# on win7.

private const string IDENTITY = #"HKEY_LOCAL_MACHINE\Ident";
private const string NAME = "Name";
string DeviceName = (string)Registry.GetValue(IDENTITY, NAME, "NAME");

We developed an application for the same device, we used this sentense to get device name.
Private Sub deviceidt_ParentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deviceidt.ParentChanged
Dim deviceidn As String = System.Net.Dns.GetHostName
deviceidt.Text = deviceidn
End If
End Sub

Related

Remote logout tool

I'm writing a remote log out tool for the school I attend. As system admins, we use it to log out users after our on-campus labs have closed to make sure that all the computers get updates at night. With windows 7, the tool we have now works fine. But we're updating to windows 10 for all of our machines and the tool has mysteriously stopped functioning. It's written in VB.net as of right now (open to a change to c# if needed). Currently we have 2 main functions for the program:
Private Sub LogOut()
Dim AdminAccount As String = txtUsr.Text
Dim AdminDomain As String = txtDomain.Text
Dim AdminPassword As String = txtPwd.Text
Dim ShutDownLocal As String = "c:\bin\"
Dim LogOutProgram As String = "c:\bin\Logout.cmd"
Dim TargetMachine As String = cboDom.Text & ComboBox1.Text & "p" & txtMachine.Text & txtDomain.Text
Dim ShutDownCommand As String = "shutdown -t 300 /r /m \\" & TargetMachine
If RunAs.RunAs(AdminAccount, AdminPassword, AdminDomain, ShutDownCommand, ShutDownLocal) Then
Status.Text = "5 Minute Logout sent to machine"
End If
End Sub
and
Public Shared Function RunAs(ByVal UserName As String, _
ByVal Password As String, _
ByVal DomainName As String, _
ByVal CommandLine As String, _
ByVal StartIn As String) As Boolean
Dim iRet As Integer
Dim si As New STARTUPINFO
Dim pi As PROCESS_INFORMATION
si.cb = Marshal.SizeOf(si)
si.wShowWindow = 0
iRet = CreateProcessWithLogonW(UserName, DomainName, Password, _
LOGON_WITH_PROFILE, Nothing, CommandLine, _
NORMAL_PRIORITY_CLASS, 0, StartIn, si, pi)
If iRet = 0 Then
MessageBox.Show("Password incorrect.", "Error")
Return False
Else
CloseHandle(pi.hThread)
CloseHandle(pi.hProcess)
Return True
End If
End Function
Currently this functions absolutely fine on windows 7 machines but for attempting it on windows 10 machines we either get "access denied(5)" or "The entered computer name is not valid or remote shutdown is not supported on the target computer. Check the name and then try again or contact your system administrator.(53)"
I already checked with the administrator and he said that it is enabled. We use a domain level firewall so the individual computers aren't rejecting the connection. Every machine has the same administrator groups (Which I am using the credentials for every attempt). I'm not sure of any other solutions to look into. Sorry for the wall of text, any solutions can be tested for the most part. No third party software unfortunately.
Thanks!

TesseractEngine does not release the traineddata file

After I run the following code I can not delete the *.traineddata file in datapath folder, until I completely closes the program.
Shared Function GetOcrText(ByVal imagePath As String,
ByVal datapath As String,
ByVal languages As IEnumerable(Of String)) As String
Dim languagesStr = String.Join("+", languages)
Dim resultText As String = ""
Using engine = New TesseractEngine(datapath, languagesStr, EngineMode.Default)
Using img = Pix.LoadFromFile(imagePath)
Using page = engine.Process(img)
resultText = page.GetText()
End Using
End Using
End Using
Return resultText
End Function
Am I wrong about something?
What should I do to be able to delete the file?
Use 3.2.0-alpha4 version of .Net wrapper for tesseract-ocr.
I tried your code with this version and everything works fine.

Programmatically create a SQL Server Compact database on the client machines

I have recently started experimenting with SQL Server Compact and EF6. I am currently using the model first approach and generating my classes and tables from it. I am curious though, about one thing. How can I get my program to dynamically create the database. It exists on my machine as I created it with the SQL Server Compact/SQLite toolkit, but when the program is deployed to client computers, the database will need to be created.
I would want to prompt them on first run for a good location, then create the entire DB schema and just use that in the future. I looked into this guide but vs started complaining about it not working because I didn't use a code-first approach.
If you need more info let me know! Thanks.
I have a little app I'm working on using SQL CE and EF and I deploy the template database when the app is installed (clickonce). Then I use a spash screen on application start to either load a previously created database or let the user create a new one.
When they create a new db I simply prompt them for a location and copy the template database out to their desired location with their desired name. I've also set it up to use the deployed database without giving them the opportunity have multiple database files.
We are dealing with a few pieces here as follows:
SQL CE database file
My stock/template .sdf file sits in my project folder and is included in the project within Visual Studio (I'm using 2015). Rightclick on the file in the Solution Explorer and select properties you want to set the following:
Build Action - Content
Copy to Output Directory - Copy always
Create global variable
Either use an existing module file or create a new one that looks like this:
Public Module Globals
Friend g_recipeData As RecipeEntities
End Module
Create setting for last file path
Rightclick on your project name in the solution explorer and pick Properties. Click the Settings tab and add a new setting as follows:
Name: lastpath
Type: String
Scope: User
Value:
Create splash screen form (frmSplash)
Mine looks like this:
Controls on the form are as follows:
txtFile
cmdSelectDatabase
cmdNew
cmdOpen
cmdExit
Splash Screen (frmSplash) Code
Region "Form Methods"
Private Sub OnFormLoad() Handles Me.Load
txtFile.Text = My.Settings.lastpath
If txtFile.Text <> "" Then
cmdOpen.Enabled = True
cmdOpen.Select()
Else
cmdNew.Select()
End If
End Sub
Private Sub FileSelect()
Try
Dim openFileDialog As New OpenFileDialog()
openFileDialog.Filter = "sdf files (*.sdf)|*.sdf|All files (*.*)|*.*"
openFileDialog.FilterIndex = 1
openFileDialog.RestoreDirectory = True
Dim result As DialogResult = openFileDialog.ShowDialog(Me)
If result = DialogResult.Cancel Then
cmdSelectDatabase.Select()
Exit Sub
End If
txtFile.Text = openFileDialog.FileName
If txtFile.Text <> "" Then
cmdOpen.Enabled = True
cmdOpen.Select()
My.Settings.lastpath = openFileDialog.FileName
My.Settings.Save()
Else
cmdOpen.Enabled = False
cmdSelectDatabase.Select()
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
Finally
End Try
End Sub
Private Sub SetConnectionString()
Try
Dim providerName As String = "System.Data.SqlServerCe.4.0"
Dim datasource As String = txtFile.Text
Dim sqlCeBuilder As New SqlCeConnectionStringBuilder
sqlCeBuilder.DataSource = datasource
sqlCeBuilder.PersistSecurityInfo = True
g_SQLCeConnectionString = sqlCeBuilder.ConnectionString
Dim providerString As String = sqlCeBuilder.ToString()
Dim entityBuilder As New EntityConnectionStringBuilder()
entityBuilder.Provider = providerName
entityBuilder.ProviderConnectionString = providerString
entityBuilder.Metadata = "res://*/RecipeModel.csdl|res://*/RecipeModel.ssdl|res://*/RecipeModel.msl"
Dim c As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim section As ConnectionStringsSection = DirectCast(c.GetSection("connectionStrings"), ConnectionStringsSection)
g_EntityConnectionString = entityBuilder.ConnectionString
section.ConnectionStrings("RecipeEntities").ConnectionString = g_EntityConnectionString
c.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("connectionStrings")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
End Try
End Sub
Private Sub CreateDatabase()
Try
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "sdf files (*.sdf)|*.sdf"
saveFileDialog.Title = "Create Database"
saveFileDialog.FilterIndex = 1
If saveFileDialog.ShowDialog() = DialogResult.OK Then
File.Copy(Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "rw.sdf"), saveFileDialog.FileName, True)
Dim strPathandFile As String = saveFileDialog.FileName
txtFile.Text = strPathandFile
My.Settings.lastpath = strPathandFile
My.Settings.Save()
cmdOpen.Enabled = True
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
End Try
End Sub
Private Sub LoadMainApplication()
Try
Dim objNewForm As New FrmMain
objNewForm.Show()
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
End Try
End Sub
End Region
Region "Event Handlers"
Private Sub cmdSelectDatabase_Click(sender As Object,
e As EventArgs) Handles cmdSelectDatabase.Click
FileSelect()
cmdOpen.Select()
End Sub
Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdExit.Click
Me.Close()
End Sub
Private Sub cmdOk_Click(sender As Object, e As EventArgs) Handles cmdOpen.Click
Me.Cursor = Cursors.WaitCursor
SetConnectionString()
LoadMainApplication()
Me.Cursor = Cursors.Default
End Sub
Private Sub txtFile_Validated(sender As Object, e As EventArgs) Handles txtFile.Validated
If txtFile.Text.Length = 0 Then
cmdOpen.Enabled = False
Else
cmdOpen.Enabled = True
End If
End Sub
Private Sub cmdNew_Click(sender As Object,
e As EventArgs) Handles cmdNew.Click
CreateDatabase()
SetConnectionString()
LoadMainApplication()
End Sub
Private Sub CatchEnterKey(ByVal sender As Object,
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles txtFile.KeyPress, txtPassword.KeyPress
If e.KeyChar = ChrW(Keys.Enter) Then
cmdOk_Click(sender, e)
e.Handled = True
Exit Sub
End If
End Sub
Set global variable value
On the form of your main application (frmMain above) add the following to the constructor:
Public Sub New()
InitializeComponent()
g_recipeData = New RecipeEntities
End Sub
If you perform the above action when you create the variable in the module file then the connection string for the entity is set and you can't change it. You must set the connection string in app.config (using the above code) first and then the entity will use desired connection string when instantiated.
I think that's the basics for now. I highly recommend you reading through it again now that I'm done. I made some corrections and even added a step for the lastpath setting. Just hit me up if something isn't working or is confusing and I'll do my best to help. Good luck!

How to hide publishing progress bar for ExportAsFixedFormat

I am trying to convert Excel file to PDF using interop.excel, while executing ExportAsFixedFormat 'publishing' progress bar displays on the site. Is there any way to hide this? I found this issue for Excel files having size above 300KB.
Code is given below:
//(tried using Application instead of ApplicationClass)
Microsoft.Office.Interop.Excel.ApplicationClass excelApplication = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelApplication.ScreenUpdating = false;
excelApplication.DisplayAlerts = false;
excelApplication.Visible = false;
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
return false;
}
var exportSuccessful = true;
try
{
excelApplication.AlertBeforeOverwriting = false;
excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);
}
catch (System.Exception ex)
{
exportSuccessful = false;
}
I can't find any solution. My project is a C# web application.
It took me a few days to figure out, but finally here is a workarround which uses some WinAPI functions to observe windows events. While the hook is active, every new window is compared to whether its class is the same one as the PDF save dialog class. If that's the case, the window gets hidden.
Thanks for solution ideas go to some chinese guys:
http://www.itjie.wang/officebase/516998.html
Usage requirement:
OS (= Operating System) must be Windows because of WinAPI usage.
Warning:
If the "SetWinEventHook" isn't stopped again due to some errors, it is better to restart your system, otherwise you could run into some serious problems with Windows.
Note:
By default, the PDF save dialog doesn't appear regularly. It depends on the time necessary to save the PDF file. If it takes longer the save popup will show up. If it takes shorter the save popup won't show up. Anyway, you don't have to worry about whether the save dialog would appear or not, the code already does this for you.
Instruction:
In your Excel workbook, if you don't already have a module, create a new one (name doesn't matter) & paste following code:
' WINDOWS API FUNCTIONS:
Private Declare Function SetWinEventHook Lib "user32" (ByVal eventMin As Long, ByVal eventMax As Long, ByVal hmodWinEventProc As Long, ByVal pfnWinEventProc As Long, ByVal idProcess As Long, ByVal idThread As Long, ByVal dwFlags As Long) As Long
Private Declare Function UnhookWinEvent Lib "user32" (ByVal hWinEventHook As Long) As Long
Private Declare Function apiGetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassname As String, ByVal nMaxCount As Long) As Long
Private Declare Function apiShowWindow Lib "user32" Alias "ShowWindow" (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
' CONSTANT VARIABLES:
Private Const SW_HIDE = 0
Private Const DLG_CLSID = "CMsoProgressBarWindow"
Private Const EVENT_SYSTEM_FOREGROUND = &H3&
Private Const WINEVENT_OUTOFCONTEXT = 0
' GLOBAL VARIABLES:
Dim long_WinEventHook As Long
Public Function StartEventHook() As Long
long_WinEventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, 0&, AddressOf WinEventFunc, 0, 0, WINEVENT_OUTOFCONTEXT)
StartEventHook = long_WinEventHook
End Function
Public Sub StopEventHook()
Dim b_unhooked As Boolean
If long_WinEventHook = 0 Then
MsgBox "WinEventHook couldn't be stopped! " & _
"Variable 'long_WinEventHook' is empty! " & _
"Better restart Windows now!"
Exit Sub
End If
b_unhooked = UnhookWinEvent(long_WinEventHook)
If b_unhooked = True Then
Else
MsgBox "WinEventHook couldn't be stopped! " & _
"Variable 'b_unhooked' is false! " & _
"Better restart Windows now!"
End If
End Sub
' CALLBACK FUNC OF "SetWinEventHook" (DEFINE ACTIONS TO RUN ON THE EVENTS):
' http://stackoverflow.com/questions/20486944/detecting-in-vba-when-the-window-containing-an-excel-instance-becomes-active
Public Function WinEventFunc(ByVal HookHandle As Long, ByVal LEvent As Long, ByVal hWnd As Long, ByVal idObject As Long, ByVal idChild As Long, ByVal idEventThread As Long, ByVal dwmsEventTime As Long) As Long
'This function is a callback passed to the win32 api
'We CANNOT throw an error or break. Bad things will happen
On Error Resume Next
Dim l_handle As Long
Dim s_buffer As String
Dim b_visible As Boolean
Dim i_bufferLength As Integer
s_buffer = String$(32, 0)
i_bufferLength = apiGetClassName(hWnd, s_buffer, Len(s_buffer))
If Left(s_buffer, i_bufferLength) = DLG_CLSID Then
b_visible = apiShowWindow(hWnd, SW_HIDE)
WinEventFunc = hWnd
End If
End Function
In your VBA code, when you want to save your excel workbook as PDF, you would call above macros like this:
' ADD WINDOWS EVENT HOOK BEFORE SAVING:
Application.Run XL_WB.Name & "!StartEventHook"
' SAVE EXCEL AS PDF:
' https://msdn.microsoft.com/de-de/library/microsoft.office.tools.excel.worksheetbase.exportasfixedformat.aspx
XL_WB.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\PDF.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
' REMOVE WINDOWS EVENT HOOK AFTER SAVING:
Application.Run XL_WB.Name & "!StopEventHook"
In the above VBA code example "XL_WB" is a variable. You have to adjust it to your needs. For example use "ActiveSheet" instead.
From following other websites users also asked for help with that particular problem:
https://social.msdn.microsoft.com/Forums/office/en-US/e6078904-0715-46a2-8937-c38626464425/exportasfixedformat-progress-bar-can-you-hide-it?forum=exceldev
http://www.vbaexpress.com/forum/archive/index.php/t-41431.html
http://www.excelbanter.com/showthread.php?t=446463
...

Difference in Management.ManagementObject between XP and Win7

I have two OSes set up, a win7 and an XP, both them are in the same WORKGROUP (none of them is in a domain this way)
I'm trying to get the WorkGroup name of the computer with this code:
VB.NET:
Public Function GetWorkGroup() As String
Dim computer_system As New Management.ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName))
Dim result As Object = computer_system("Workgroup")
Return result.ToString()
End Function
C#:
public string GetWorkGroup()
{
Management.ManagementObject computer_system = new management.ManagementObject(string.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName));
object result = computer_system("Workgroup");
return result.ToString();
}
This does work on Win7, but on XP computer_system("Workgroup") results in Nothing.
If I want to make it work I have to make the following modification:
VB.NET:
Dim result As Object = computer_system("Domain")
C#:
object result = computer_system("Domain");
This works on both Win7 and XP, gaves back the correct Workgroup name, but cleary somethings wrong if I get back the Workgroup name with the Domain property on XP.
Could someone explain please why does XP handles it's Workgroup as a Domain? thanks.

Categories