XpsDocument.SignDigitally throws NullReferenceException on IsSignable - digital-signature

I ran into a problem with the method mentioned in the title. If I try to sign an XPS document, it runs into NullReferenceException:
at System.Windows.Xps.Packaging.XpsDocument.get_IsSignable()
at System.Windows.Xps.Packaging.XpsDocument.SignDigitally(X509Certificate certificate, Boolean embedCertificate, XpsDigSigPartAlteringRestrictions restrictions, String signatureId, Boolean testIsSignable)
at System.Windows.Xps.Packaging.XpsDocument.SignDigitally(X509Certificate certificate, Boolean embedCertificate, XpsDigSigPartAlteringRestrictions restrictions)
Any advise will appreciated.
if (sign_digitally)
{
UserCertificateSelector selector = new UserCertificateSelector();
if (selector.ShowDialog() == true)
{
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
#if DEBUG
X509CertificateCollection collection = certStore.Certificates;
#else
X509CertificateCollection collection = certStore.Certificates.Find(X509FindType.FindByThumbprint, selector.SelectedCertificate.CertificateThumbPrint,true);
#endif
if (collection.Count > 0)
{
xpsDoc.SignDigitally(collection[0], true, XpsDigSigPartAlteringRestrictions.None);
}
}
}
...

Make sure you deal with XPS file format, not OXPS. Both can be open as XpsDocument but only XPS can be signed. You can check "XpsDocument.IsSignable" flag once you open the file - for OXPS it will be null.

Related

Why I can not disable SSLv3?

I have disabled sslv3 in server side like this :
char certPass[] = "***";
char certAliaMainPass[] = "***";;
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(certPath), certPass);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, certAliaMainPass);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(iPort);
String[] protocols = sslServerSocket.getEnabledProtocols();
Set<String> set = new HashSet<String>();
for (String s : protocols) {
if (s.equals("SSLv3")) {
continue;
}
set.add(s);
}
sslServerSocket.setEnabledProtocols(set.toArray(new String[0]));
but client which used "SSLv3" still can connect to server, how can I do for this issue?
Go to Java installation folder.
Open {JRE_HOME}\lib\security\java.security -file in text editor.
Go to the last line.
Delete or comment out the following line jdk.tls.disabledAlgorithms=SSLv3

OrganizationServiceProxy: No authentication error when wrong password is setup

I'm creating Organization service proxy object using following way:
[ThreadStatic]
public static OrganizationServiceProxy OrgServiceProxy;
// ...
sLog.DebugFormat("Get AuthenticationProviderType...");
AuthenticationProviderType _crmAuthType = this.GetServerType(parameters.DiscoveryUri);
sLog.DebugFormat("Get AuthenticationProviderType - DONE!");
// ...
sLog.Info("Perform metadata download (ServiceConfigurationFactory.CreateConfiguration)...");
IServiceConfiguration<IOrganizationService> _crmServiceConfiguration = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(parameters.OrgServiceUri);
sLog.Info("Perform metadata download (ServiceConfigurationFactory.CreateConfiguration) - DONE");
// ...
// enable proxy types
var behavior = new ProxyTypesBehavior() as IEndpointBehavior;
behavior.ApplyClientBehavior(_crmServiceConfiguration.CurrentServiceEndpoint, null);
// ...
public OrganizationServiceProxy GetServiceProxy(ICRMConnectionParameters parameters)
{
// ...
ClientCredentials clientCreds = new ClientCredentials();
clientCreds.Windows.ClientCredential.UserName = parameters.UserName;
clientCreds.Windows.ClientCredential.Password = parameters.Password;
clientCreds.Windows.ClientCredential.Domain = parameters.Domain;
sLog.DebugFormat("Setup client proxy...");
OrgServiceProxy = new OrganizationServiceProxy(_crmServiceConfiguration, clientCreds);
sLog.DebugFormat("Setup client proxy - DONE.");
return OrgServiceProxy;
}
Just note here that AuthenticationProviderType and IServiceConfiguration are statically cached. This code above is part of class named CRMConnection.
I have one more abstract class (ProxyUser) which contains following property:
private CRMConnection conn;
// ...
protected OrganizationServiceProxy OrgServiceProxy
{
get
{
//return orgService;
return this.Conn.GetServiceProxy();
}
}
protected CRMConnection Conn
{
get
{
conn = conn ?? new CRMConnection();
return conn;
}
}
In another class that inherits ProxyUser I have method with following code:
ColumnSet columnSet = new ColumnSet();
ConditionExpression condition1 = new ConditionExpression("new_id", ConditionOperator.NotNull);
FilterExpression filter = new FilterExpression(LogicalOperator.And);
filter.AddCondition(condition1);
QueryExpression query = new QueryExpression()
{
EntityName = new_brand.EntityLogicalName,
ColumnSet = columnSet,
Criteria = filter,
NoLock = true
};
EntityCollection res = OrgServiceProxy.RetrieveMultiple(query);
And now we come to the point :)
If I setup correct parameters - organization service url, discovery service url, username, password and domain, everything works as expected. BUT, in case when wrong password is set, in line below, service is simply unresponsive. It doesn't happen anything.
EntityCollection res = OrgServiceProxy.RetrieveMultiple(query);
Of course, I'm expecting authentication failed error. Any suggestions what I'm missing here?
Thanks in advance!
I solved this problem with adding line below in GetServiceProxy method - when ClientCredentials are created:
clientCreds.SupportInteractive = false;
I figured this out after I moved whole logic in console app. When wrong password is set and app is in debug mode, I'm getting windows login prompt. Then I found this answer.

Downloading bulk files from sharepoint library

I want to download the files from a sharepoint document library through code as there are thousand of files in the document library.
I am thinking of creating console application, which I will run on sharepoint server and download files. Is this approach correct or, there is some other efficient way to do this.
Any help with code will be highly appreciated.
Like SigarDave said, it's perfectly possible to achieve this without writing a single line of code. But if you really want to code the solution for this, it's something like:
static void Main(string[] args)
{
// Change to the URL of your site
using (var site = new SPSite("http://MySite"))
using (var web = site.OpenWeb())
{
var list = web.Lists["MyDocumentLibrary"]; // Get the library
foreach (SPListItem item in list.Items)
{
if (item.File != null)
{
// Concat strings to get the absolute URL
// to pass to an WebClient object.
var fileUrl = string.Format("{0}/{1}", site.Url, item.File.Url);
var result = DownloadFile(fileUrl, "C:\\FilesFromMyLibrary\\", item.File.Name);
Console.WriteLine(result ? "Downloaded \"{0}\"" : "Error on \"{0}\"", item.File.Name);
}
}
}
Console.ReadKey();
}
private static bool DownloadFile(string url, string dest, string fileName)
{
var client = new WebClient();
// Change the credentials to the user that has the necessary permissions on the
// library
client.Credentials = new NetworkCredential("Username", "Password", "Domain");
var bytes = client.DownloadData(url);
try
{
using (var file = File.Create(dest + fileName))
{
file.Write(bytes, 0, bytes.Length); // Write file to disk
return true;
}
}
catch (Exception)
{
return false;
}
}
another way without using any scripts is by opening the document library using IE then in the ribbon you can click on Open in File Explorer where you can then drag and drop the files right on your desktop!

How to Get Project Type Guid of selected project in the Solution Explorer by using VS Package

I've created the simple VS Package for adding new item in the context menu of solution explorer. In that I need to check Selected Project's Project Type GUID. How can i get this.
For example, One Solution contains the three different type of projects, like WindowFormsApplication, MVC Projects,WebApplication. While select the MVC Projects, we need to get that ProjectType GUID.
I've tried the followings in my Package.cs,
IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection));
monitorSelection.GetCurrentSelection(out hierarchyPtr, out projectItemId, out mis, out selectionContainerPtr);
IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy;
if (hierarchy != null)
{
object prjItemObject;
hierarchy.GetProperty(projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out prjItemObject);
string projectTypeGuid;
Project prjItem = prjItemObject as Project;
projectTypeGuid = prjItem.Kind;
}
In that I get GUID as "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC" for all selected Projects.
Could anyone please help me this?
I've found answer for this,
Reference: https://www.mztools.com/articles/2007/MZ2007016.aspx
public string GetProjectTypeGuids(EnvDTE.Project proj)
{
string projectTypeGuids = "";
object service = null;
Microsoft.VisualStudio.Shell.Interop.IVsSolution solution = null;
Microsoft.VisualStudio.Shell.Interop.IVsHierarchy hierarchy = null;
Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject aggregatableProject = null;
int result = 0;
service = GetService(proj.DTE, typeof(Microsoft.VisualStudio.Shell.Interop.IVsSolution));
solution = (Microsoft.VisualStudio.Shell.Interop.IVsSolution)service;
result = solution.GetProjectOfUniqueName(proj.UniqueName, out hierarchy);
if (result == 0)
{
aggregatableProject = (Microsoft.VisualStudio.Shell.Interop.IVsAggregatableProject)hierarchy;
result = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids);
}
return projectTypeGuids;
}
public object GetService(object serviceProvider, System.Type type)
{
return GetService(serviceProvider, type.GUID);
}
public object GetService(object serviceProviderObject, System.Guid guid)
{
object service = null;
Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider = null;
IntPtr serviceIntPtr;
int hr = 0;
Guid SIDGuid;
Guid IIDGuid;
SIDGuid = guid;
IIDGuid = SIDGuid;
serviceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)serviceProviderObject;
hr = serviceProvider.QueryService(ref SIDGuid, ref IIDGuid, out serviceIntPtr);
if (hr != 0)
{
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
}
else if (!serviceIntPtr.Equals(IntPtr.Zero))
{
service = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(serviceIntPtr);
System.Runtime.InteropServices.Marshal.Release(serviceIntPtr);
}
return service;
}
}
Its working fine for my requirement.

Is it possible to get the HWID on linux and windows in C# without WMI?

Hi :) I'm writing a C# application and need to get the HWID code for the computer the code is running on. Since this is a console, i need to figure out a way to find the HWID for the CPU, motherboard and HDD, without using the the WMI. Since the system.management is not available on linux, i need it without using that. is it possible to find the HWID without the WMI? Or could i find a way to use the WMI for linux to find the HWID?
Is it possible in C# to do this? I would appreciate if anyone told me how, or pointed me in the right direction to get started. thank you all!
Try this link, not sure if it will work on linux though.
Updated
private string GetUID()
{
StringBuilder strB = new StringBuilder();
Guid G = new Guid(); HidD_GetHidGuid(ref G);
strB.Append(Convert.ToString(G));
IntPtr lHWInfoPtr = Marshal.AllocHGlobal(123); HWProfile lProfile = new HWProfile();
Marshal.StructureToPtr(lProfile, lHWInfoPtr, false);
if (GetCurrentHwProfile(lHWInfoPtr))
{
Marshal.PtrToStructure(lHWInfoPtr, lProfile);
strB.Append(lProfile.szHwProfileGuid.Trim(new char[] { '{', '}' }));
}
Marshal.FreeHGlobal(lHWInfoPtr);
SHA256CryptoServiceProvider SHA256 = new SHA256CryptoServiceProvider();
byte[] B = Encoding.Default.GetBytes(strB.ToString());
string outStr = BitConverter.ToString(SHA256.ComputeHash(B)).Repla ce("-", null);
for(int i = 0;i < 64; i++)
{
if (i % 16 == 0 && i != 0)
outStr = outStr.Insert(i, "-");
}
return (outStr);
}
[DllImport("hid.dll")]
private static extern void HidD_GetHidGuid(ref Guid GUID);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetCurrentHwProfile(IntPtr fProfile);
[StructLayout(LayoutKind.Sequential)]
class HWProfile
{
public Int32 dwDockInfo;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 39)]
public string szHwProfileGuid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szHwProfileName;
}

Resources