How I can use Shell32.dll in Silverlight OOB - pinvoke

I'd like to get the target information from a shortcut file using my silverlight OOB app, so I'm going to make the following code to work in my silverlight OOB. It seems I have to used P/Invoke to use Shell32.dll, but I'm not sure how I can use Folder, FolderItem, and ShellLinkObject? Most references explain how I can use the functions in the .dll using P/invoke:( Please give me any comments or sample code/links:)
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = Path.GetDirectoryName(shortcutFilename);
string filenameOnly = Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
MessageBox.Show(link.Path);
return link.Path;
}
return String.Empty; // Not found
}

I found a solution.
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFile);
string filenameOnly = System.IO.Path.GetFileName(shortcutFile);
dynamic shell = AutomationFactory.CreateObject("Shell.Application");
dynamic folder = shell.NameSpace(pathOnly);
dynamic folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
dynamic link = folderItem.GetLink;
return "\""+link.Path +"\"" + " " + link.Arguments;
}
return String.Empty; // Not found
}

Related

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;
}
}

Identify a file or directory on a SSH machine using net.schmizz.sshj.sftp.SFTPClient api.

I want to identify whether a the given path is a valid path for file or directory using net.schmizz.sshj.sftp.SFTPClient api and based on i need to take decision that if it is a valid file path then i need to access its parent directory. my code looks like below>
SSHClient ssh = new SSHClient();
String rsaKey = "e3:27:12:a9:62:9a:46:cc:98:ee:0d:b7:38:72:a0:63";
String host = "10.235.1.154";
String uName = "root";
String pwd = "pspl#123";
String url = "/root/ram2.log/";
String testUrl = host + url;
ssh.addHostKeyVerifier(rsaKey);
List fileItems = new ArrayList();
1.try {
2. ssh.connect(host);
3. ssh.authPassword(uName,pwd);
4. SFTPClient sftp = ssh.newSFTPClient();
5.
6. if(testUrl.startsWith(host)){
7. String[] splitedStrings = testUrl.split(host);
8. String str = splitedStrings[1];
9. url = str;
10. }else{
11. url = url;
12. }
13.
14.
15. List<RemoteResourceInfo> fileInfoList = sftp.ls(url, new RemoteResourceFilter() {
16. public boolean accept(RemoteResourceInfo rrInfo) {
17. return rrInfo.getName().charAt(0) != '.';
18. }
19. });
20.
21.
22. for (RemoteResourceInfo fileInfo : fileInfoList) {
23. //files.add(str + "/" + fileInfo.getName());
24. String fileName = fileInfo.getName();
25. if (fileInfo.isDirectory()) {
FileItem childFileItem = new FileItem();
childFileItem.setPath(host + url + fileName);
fileItems.add(childFileItem);
} else {
int dotIndex = fileName.lastIndexOf('.');
String ext = dotIndex > 0 ? fileName
.substring(dotIndex + 1) : "";
FileItem childFileItem = new FileItem();
childFileItem.setPath(host + url + fileName);
childFileItem.setDirectory(false);
fileItems.add(childFileItem);
}
}
} catch (IOException e) {
System.out.println("Couldn't resolve host : {} "+ host);
}
return fileItems;
Problem: Line no. 15 is throwing error saying no such file if I m giving the path as "/root/ram2.log/" even though the file ram2.log does exis on server.
Any help on this wud be graet helpful.
You can use lstat to get information about file system objects.
FileAttributes attributes = sftp.lstat(url);
if (attributes.getType() == FileMode.Type.DIRECTORY) {
...
}
But i think your actual problem is that something is odd with the directory "/root/ram2.log/". Maybe no permission, maybe it's not visible to you, maybe it contains a file with a name that isn't encoded properly.

Cached Variables in VSTO Office 2010

After having a look around the web, I have found the following posts (below) which are quite similar to my problem. However, after trying the solutions, I am still stuck.
VSTO Frustration
Setting cached variables in VSTO 3.0
Basically, I want to populate some data in a Excel file on a web server before I send it to the client.
Here is my code in the Workbook:
namespace Inno.Data.Excel
{
public partial class ThisWorkbook
{
[Cached]
public DataSet Config = new DataSet();
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
//InitializeCachedData();
var baseUrl = (string)Config.Tables["Config"].Rows[0].ItemArray[0];
var streamIds = (string)Config.Tables["Config"].Rows[0].ItemArray[1];
MessageBox.Show(baseUrl + " " + streamIds);
}
}
}
and on the server side I have the following:
let rootUrl = Uri(x.Request.Url.GetLeftPart(UriPartial.Authority))
let setUpData (report : Report) (sd : ServerDocument) =
let url = rootUrl.AbsoluteUri
let streamIds = String.Join(",", report.series |> Seq.map(fun s -> s.id))
let dt = new System.Data.DataTable("Config")
dt.Columns.Add("BaseUrl", typeof<String>) |> ignore
dt.Columns.Add("StreamIds", typeof<String>) |> ignore
dt.Rows.Add([|box url; box streamIds|]) |> ignore
dt.AcceptChanges()
let cache = sd.CachedData.HostItems.["Inno.Data.Excel.ThisWorkbook"]
let urlItem = cache.CachedData.["Config"]
urlItem.SerializeDataInstance(dt)
sd.Save()
sd.Close()
let initialiseDocument (report : Report) (path : string) =
let fileName = report.name.Replace(" ", "_") + ".xlsx"
let sd = (new ServerDocument(path))
sd |> setUpData report
fileName
let docPath = x.Request.MapPath(Path.Combine(liveReportPath, "Inno.Data.Excel.xlsx"))
let fileName = initialiseDocument report docPath
x.File(File.OpenRead(docPath), "application/vnd.ms-excel", fileName) :> ActionResult
However, when I go to open the file after it has downloaded, I get the following error:
Microsoft.VisualStudio.Tools.Applications.Runtime.CannotFindObjectToFillException: Cannot find any public instance member with ID Config in object Inno.Data.Excel.ThisWorkbook.
Things I have tried:-
Using a simple string rather than a DataSet
Calling StartCaching("Config")
Manipulating the ServerDocument in memory using the byte[] file overload
Copying the original Excel file and operating on the copy
But now I'm out of ideas. I see that a fair number of people have had this error, and as is pointed out in this post, there was a known bug in VSTO 3.0 with manipulating files in memory.
Thanks in advance.

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.