Cast issue with CaptureFileAsync() - vb.net

I'm trying to figure out how to call windows camera UI from a windows form.
I did this and it does compile:
Public Function ShootPicture() As StorageFile
Dim captureUI As New CameraCaptureUI
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg
captureUI.PhotoSettings.AllowCropping = False
Dim GetPhotoTask As Task(Of StorageFile) = captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo)
GetPhotoTask.Wait() ' Blocks current thread until CaptureFileAsync task completes'
Dim result As StorageFile = GetPhotoTask.Result
Return result
End Function
But there is a 'System.InvalidCastException' execution error on .capturefileAsync() : type 'System._ComObject' cannot be casted as 'System.threading.tasks.task'
Would anyone have any idea on how to fix this? Thanks
If it can help here is the c# code translation:
public StorageFile ShootPicture()
{
CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
captureUI.PhotoSettings.AllowCropping = false;
Task<StorageFile> GetPhotoTask = captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
GetPhotoTask.Wait();
// Blocks current thread until CaptureFileAsync task completes
StorageFile result = GetPhotoTask.Result;
return result;
}

CaptureFileAsync returns an IAsyncOperation, so try using await instead of a Task:
Dim result As StorageFile = Await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo)

Related

Telegram API Client doesn't find group/send message

Im using TLSharp API Client for sending messages to groups, TLSharp is C#, but im trying to use it for VB.NET
C# Code:
//get user dialogs
var dialogs = (TLDialogsSlice) await client.GetUserDialogsAsync();
//find channel by title
var chat = dialogs.Chats
.Where(c => c.GetType() == typeof(TLChannel))
.Cast<TLChannel>()
.FirstOrDefault(c => c.Title == "<channel_title>");
//send message
await client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = chat.Id, AccessHash = chat.AccessHash.Value }, "OUR_MESSAGE");
My VB.NET Code:
Dim dialogs = Await ((Await client.GetUserDialogsAsync()))
Dim chat = dialogs.Chats.lists.Where(Function(c) c.[GetType]() = GetType(TLChat)).Cast(Of TLChat)().FirstOrDefault(Function(c) c.title = "Group1")
Dim ChatId
Await client.SendMessageAsync(New TLInputPeerChat() {ChatId = chat.Id}, "TEST MSG")
The error i get:
Could not find public member 'GetAwaiter' in type 'TLDialogs'.'
I know it's not practical to convert it to vb.net, but I need it to integrate it into a project written in vb
I don't think that the client.GetUserDialogsAsync() method returns anything that is awaitable, so you should probably only have one Await in the line Dim dialogs = Await ((Await client.GetUserDialogsAsync())), and it may also require a cast:
Dim dialogs = DirectCast(Await client.GetUserDialogsAsync(), TLDialogsSlice)

SSRS Report executes directly but WCF ReportExporter.Export method returns null Result and no errors

I have a report that is hosted in SQL Server 2012 SSRS and it executes fine through the browser. I am trying to run it using WCF as a Service Reference for the SSRS 2005 asmx from a ASP.Net web project and return it as a PDF using the ReportExporter.Export() method; however, it is not returning a result at all and the warnings array is empty. So, how can I troubleshoot the process to see where the difficulty is? I did not find any errors in the SSRS Log file even when I set it to verbose; nor did I find any errors in the standard SQL Log.
Here is my code:
NOTE: the call ReportExporter.Export(..) is to a method that encapsulates the execution of the webServiceProxy to the Service Reference.
{
IList<SSRS_Reports.ParameterValue> parameters = new List<SSRS_Reports.ParameterValue>();
parameters.Add(new SSRS_Reports.ParameterValue { Name = "paramId", Value = _paramId.ToString() }); }
byte[] result = null;
string extension = string.Empty;
string mimeType = string.Empty;
string encoding = string.Empty;
string reportName = "/baseFolder/ReceiptReport";
SSRS_Reports.Warning[] warnings = null;
string[] streamIDs = null;
string uN = ConfigurationManager.AppSettings["rptUName"].ToString();
string uP = ConfigurationManager.AppSettings["rptPWD"].ToString();
string uD = ConfigurationManager.AppSettings["rptDomain"].ToString();
//NOTE: the call "ReportExporter.Export(..) is to a method that encapsulates the execution of the webServiceProxy to the Service Reference.
ReportExporter.Export("ReportExecutionServiceSoap",
new System.Net.NetworkCredential(uN, uP, uD),
reportName,
parameters.ToArray(),
ExportFormat.PDF,
out result,
out extension,
out mimeType,
out encoding,
out warnings,
out streamIDs);
if (result != null)
{
//create a file and then show in browser
_mPDFFile = randomName() + ".pdf";
_mPDFPath = HttpRuntime.AppDomainAppPath + "\\pdf\\" + _mPDFFile;
//clear files older than today
Lib.FileManager.ManageFiles(HttpRuntime.AppDomainAppPath + "\\pdf", "*.pdf", -1);
if (File.Exists(_mPDFPath))
{
File.Delete(_mPDFPath);
}
FileStream stream = File.Create(_mPDFPath, result.Length);
stream.Write(result, 0, result.Length);
stream.Close();
return true;
}
}

Adobe Illustrator - Scripting crashes when trying to fit to artboards command

activeDocument.fitArtboardToSelectedArt()
When calling this command, AI crashes on AI 5.1/6 32bit and 64bit versions. I can use the command from the menu. Has anyone encountered this? does anyone know of a work around?
The full code.
function exportFileToJPEG (dest) {
if ( app.documents.length > 0 ) {
activeDocument.selectObjectsOnActiveArtboard()
activeDocument.fitArtboardToSelectedArt()//crashes here
activeDocument.rearrangeArtboards()
var exportOptions = new ExportOptionsJPEG();
var type = ExportType.JPEG;
var fileSpec = new File(dest);
exportOptions.antiAliasing = true;
exportOptions.qualitySetting = 70;
app.activeDocument.exportFile( fileSpec, type, exportOptions );
}
}
var file_name = 'some eps file.eps'
var eps_file = File(file_name)
var fileRef = eps_file;
if (fileRef != null) {
var optRef = new OpenOptions();
optRef.updateLegacyText = true;
var docRef = open(fileRef, DocumentColorSpace.RGB, optRef);
}
exportFileToJPEG ("output_file.jpg")
I can reproduce the bug with AI CS5.
It seems that fitArtboardToSelectedArt() takes the index of an artboard as an optional parameter. When the parameter is set, Illustrator doesn't crash. (probably a bug in the code handling the situation of no parameter passed)
As a workaround you could use:
activeDocument.fitArtboardToSelectedArt(
activeDocument.artboards.getActiveArtboardIndex()
);
to pass the index of the active artboard with to the function. Hope this works for you too.
Also it's good practice to never omit the semicolon at the end of a statement.

WMIC - how to use Lenovo SetBiosSetting method

I have a prob calling SetBiosSetting method using WMIC (and also C#)
wmic /namespace:\root\wmi path Lenovo_SetBiosSetting call SetBiosSetting "SecurityChip,Active"
wmic /namespace:\root\wmi path Lenovo_SetBiosSetting call SetBiosSetting SecurityChip,Active
wmic /namespace:\root\wmi path Lenovo_SetBiosSetting call SetBiosSetting ("SecurityChip,Active")
that gives "Invalid Number of Parameters." error, but why ?
Lenovo BIOS Deployment Guide: http://download.lenovo.com/ibmdl/pub/pc/pccbbs/thinkcentre_pdf/hrdeploy_en.pdf
Any Idea ?
I cant use VBS or PowerShell ...
Thanks,Martin
Try this in C#:
ManagementScope scope = new ManagementScope(#"\\.\root\wmi");
//
// Make change(s)
//
SelectQuery queryRead = new SelectQuery("SELECT * from Lenovo_SetBiosSetting");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, queryRead))
{
using (ManagementObjectCollection queryCollection = searcher.Get())
{
foreach (ManagementObject queryItem in queryCollection)
{
ManagementBaseObject inParams = queryItem.GetMethodParameters("SetBiosSetting");
inParams["parameter"] = "WakeOnLAN,Disable";
ManagementBaseObject outParams = queryItem.InvokeMethod("SetBiosSetting", inParams, null);
string result = outParams["return"] as string; // "Success"
}
}
}
//
// Commit to BIOS
//
queryRead = new SelectQuery("SELECT * from Lenovo_SaveBiosSettings");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, queryRead))
{
using (ManagementObjectCollection queryCollection = searcher.Get())
{
foreach (ManagementObject queryItem in queryCollection)
{
ManagementBaseObject inParams = queryItem.GetMethodParameters("SaveBiosSettings");
inParams["parameter"] = "";
ManagementBaseObject outParams = queryItem.InvokeMethod("SaveBiosSettings", inParams, null);
string result = outParams["return"] as string; // "Success"
}
}
}
The PowerShell for this is:
(gwmi -class Lenovo_SetBiosSetting -namespace root\wmi).SetBiosSetting("WakeOnLAN,Disable")
I arrived at this post trying to find a way to use WMIC to get all the objects in the Lenovo_BiosSetting class. Your syntax got me on the right track. I had to change your WMIC query to this:
wmic /namespace:\\root\wmi path Lenovo_BiosSetting get
(Note the double back slash)

Test zip password correctness in vb.net

I want to test if a zip has a particular password in vb.net. How can I create a function like check_if_zip_pass(file, pass) As Boolean?
I can't seem to find anything in the .net framework that does this already, unless I'm missing something incredibly obvious.
This method should NOT extract the files, only return True if the attempted pass is valid and False if not.
Use a 3rd party library, like DotNetZip. Keep in mind that passwords in zipfiles are applied to entries, not to the entire zip file. So your test doesn't quite make sense.
One reason WinZip may refuse to unpack the zipfile is that the very first entry is protected with a password. It could be the case that only some entries are protected by password, and some are not. It could be that different passwords are used on different entries. You'll have to decide what you want to do about these possibilities.
One option is to suppose that only one password is used on any entries in the zipfile that are encrypted. (This is not required by the zip specification) In that case, below is some sample code to check the password. There is no way to check a password without doing the decryption. So this code decrypts and extracts into Stream.Null.
public bool CheckZipPassword(string filename, string password)
{
bool success = false;
try
{
using (ZipFile zip1 = ZipFile.Read(filename))
{
var bitBucket = System.IO.Stream.Null;
foreach (var e in zip1)
{
if (!e.IsDirectory && e.UsesEncryption)
{
e.ExtractWithPassword(bitBucket, password);
}
}
}
success = true;
}
catch(Ionic.Zip.BadPasswordException) { }
return success;
}
Whoops! I think in C#. In VB.NET this would be:
Public Function CheckZipPassword(filename As String, password As String) As System.Boolean
Dim success As System.Boolean = False
Try
Using zip1 As ZipFile = ZipFile.Read(filename)
Dim bitBucket As System.IO.Stream = System.IO.Stream.Null
Dim e As ZipEntry
For Each e in zip1
If (Not e.IsDirectory) And e.UsesEncryption Then
e.ExtractWithPassword(bitBucket, password)
End If
Next
End Using
success = True
Catch ex As Ionic.Zip.BadPasswordException
End Try
Return success
End Function
I use SharpZipLib in .NET to do this, here is a link to their wiki with a helper function for unzipping password protected zip files. Below is a copy of the helper function for VB.NET.
Imports ICSharpCode.SharpZipLib.Core
Imports ICSharpCode.SharpZipLib.Zip
Public Sub ExtractZipFile(archiveFilenameIn As String, password As String, outFolder As String)
Dim zf As ZipFile = Nothing
Try
Dim fs As FileStream = File.OpenRead(archiveFilenameIn)
zf = New ZipFile(fs)
If Not [String].IsNullOrEmpty(password) Then ' AES encrypted entries are handled automatically
zf.Password = password
End If
For Each zipEntry As ZipEntry In zf
If Not zipEntry.IsFile Then ' Ignore directories
Continue For
End If
Dim entryFileName As [String] = zipEntry.Name
' to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
' Optionally match entrynames against a selection list here to skip as desired.
' The unpacked length is available in the zipEntry.Size property.
Dim buffer As Byte() = New Byte(4095) {} ' 4K is optimum
Dim zipStream As Stream = zf.GetInputStream(zipEntry)
' Manipulate the output filename here as desired.
Dim fullZipToPath As [String] = Path.Combine(outFolder, entryFileName)
Dim directoryName As String = Path.GetDirectoryName(fullZipToPath)
If directoryName.Length > 0 Then
Directory.CreateDirectory(directoryName)
End If
' Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
' of the file, but does not waste memory.
' The "Using" will close the stream even if an exception occurs.
Using streamWriter As FileStream = File.Create(fullZipToPath)
StreamUtils.Copy(zipStream, streamWriter, buffer)
End Using
Next
Finally
If zf IsNot Nothing Then
zf.IsStreamOwner = True ' Makes close also shut the underlying stream
' Ensure we release resources
zf.Close()
End If
End Try
End Sub
To test, you could create a file compare that looks at the file before it's zipped and again after it has been unzipped (size, date, etc...). You could even compare the contents if you wanted to use a simple test file, like a file with the text "TEST" inside. Lots of choices, depends on how much and how far you want to test.
There's not much built into the framework for doing this. Here's a big sloppy mess you could try using the SharpZipLib library:
public static bool CheckIfCorrectZipPassword(string fileName, string tempDirectory, string password)
{
byte[] buffer= new byte[2048];
int n;
bool isValid = true;
using (var raw = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var input = new ZipInputStream(raw))
{
ZipEntry e;
while ((e = input.GetNextEntry()) != null)
{
input.Password = password;
if (e.IsDirectory) continue;
string outputPath = Path.Combine(tempDirectory, e.FileName);
try
{
using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, n);
}
}
}
catch (ZipException ze)
{
if (ze.Message == "Invalid Password")
{
isValid = false;
}
}
finally
{
if (File.Exists(outputPath))
{
// careful, this can throw exceptions
File.Delete(outputPath);
}
}
if (!isValid)
{
break;
}
}
}
}
return isValid;
}
Apologies for the C#; should be fairly straightforward to convert to VB.NET.