Thread t = new Thread(Flashwatcher); t.Start(); //... private void Flashwatcher() { ManagementScope scope = new ManagementScope("root\\CIMV2"); scope.Options.EnablePrivileges = true; WqlEventQuery query = new WqlEventQuery(); query.EventClassName = "__InstanceCreationEvent"; query.WithinInterval = new TimeSpan(0, 0, 1); query.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"; watcher = new ManagementEventWatcher(scope, query); watcher.Start(); watcher.WaitForNextEvent(); }
c# Вставляем флэшку в компьютер и обрабатываем это событие
c# Пишем аналог КриптоАРМ Подписать и зашифровать с архивированием перед шифрованием.
Для создания Zip используем библиотеку:
using Ionic.Zip;
Сам код:
static bool SigZipEnc(string _path, bool _pin, X509Certificate2 cert,X509Certificate2 recipientCert) { try { Sign(_path,cert); CreateZipArhive(_path+".sig"); EncryptMsg(_path+".zip", recipientCert); } catch { return false; } return true; } static void CreateZipArhive(string _pathin) { using (ZipFile zip = new ZipFile()) { zip.AddFile(_pathin); zip.Save(_pathin+".zip"); } } static void EncryptMsg( string _path, X509Certificate2 recipientCert) { Byte[] msg = System.IO.File.ReadAllBytes(_path); ContentInfo contentInfo = new ContentInfo(msg); EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo); CmsRecipient recip1 = new CmsRecipient(recipientCert); envelopedCms.Encrypt(recip1); byte[] encodedMsg = envelopedCms.Encode(); System.IO.File.WriteAllBytes(_path + ".enc", encodedMsg); } public static void Sign(string _path, X509Certificate2 cert) { byte[] msgBytes = System.IO.File.ReadAllBytes(_path); ContentInfo contentInfo = new ContentInfo(msgBytes); SignedCms signedCms = new SignedCms(contentInfo); CmsSigner cmsSigner = new CmsSigner(cert); signedCms.ComputeSignature(cmsSigner); byte[] encodedMsg = signedCms.Encode(); System.IO.File.WriteAllBytes(_path + ".sig", encodedMsg); }
Cryptopro c# Get the list of all certificate containers
public class Win32 { [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool CryptAcquireContext( ref IntPtr hProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool CryptGetProvParam( IntPtr hProv, uint dwParam, [In, Out] byte[] pbData, ref uint dwDataLen, uint dwFlags); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool CryptGetProvParam( IntPtr hProv, uint dwParam, [MarshalAs(UnmanagedType.LPStr)] StringBuilder pbData, ref uint dwDataLen, uint dwFlags); [DllImport("advapi32.dll")] public static extern bool CryptReleaseContext( IntPtr hProv, uint dwFlags); }
using System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Collections; using System.Text; namespace CryptoHelper { public static class CryptoHelper { public static string[] GetContainerNames() { int BUFFSIZE = 512; ArrayList containernames = new ArrayList(); uint pcbData = 0; //String provider = null; //can use null, for default provider String provider = "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider"; String container = null; //required for crypt_verifycontext uint type = PROV_RSA_FULL; uint cspflags = CRYPT_VERIFYCONTEXT | CSPKEYTYPE; //no private key access required. uint enumflags = PP_ENUMCONTAINERS; //specify container enumeration functdionality IntPtr hProv = IntPtr.Zero; uint dwFlags = CRYPT_FIRST; bool gotcsp = Win32.CryptAcquireContext(ref hProv, container, provider, type, cspflags); if (!gotcsp) { showWin32Error(Marshal.GetLastWin32Error()); return null; } StringBuilder sb = null; Win32.CryptGetProvParam(hProv, enumflags, sb, ref pcbData, dwFlags); BUFFSIZE = (int)(2 * pcbData); sb = new StringBuilder(BUFFSIZE); /* ---------- Get KeyContainer Names ------------- */ dwFlags = CRYPT_FIRST; //required initalization while (Win32.CryptGetProvParam(hProv, enumflags, sb, ref pcbData, dwFlags)) { dwFlags = 0; //required to continue entire enumeration containernames.Add(sb.ToString()); } if (hProv != IntPtr.Zero) Win32.CryptReleaseContext(hProv, 0); if (containernames.Count == 0) return null; else return (string[])containernames.ToArray(Type.GetType("System.String")); } const uint PROV_RSA_FULL = 0x00000001; const uint CRYPT_VERIFYCONTEXT = 0xF0000000; static uint CSPKEYTYPE = 0; const uint PP_ENUMCONTAINERS = 0x00000002; const uint CRYPT_FIRST = 0x00000001; private static void showWin32Error(int errorcode) { Win32Exception myEx = new Win32Exception(errorcode); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error code:\t 0x{0:X}", myEx.ErrorCode); Console.WriteLine("Error message:\t {0}\n", myEx.Message); Console.ForegroundColor = ConsoleColor.White; } } }
c# парсим строку текст
public List<string> ParseString(string _string4Parse,string _beginVal,string _endVal) { List<string> res = new List<string>(); int _begin = 0; while ((_begin = _string4Parse.IndexOf(_beginVal, _begin)) > -1) { _begin += _beginVal.Length; int _length = _string4Parse.IndexOf(_endVal, _begin)-_begin; res.Add(_string4Parse.Substring(_begin, _length)); } return res; }
c# Переводим с помощью Bing Api translator
using System; using System.Text; using System.Net; using System.IO; using System.Runtime.Serialization.Json; using System.Runtime.Serialization; using System.Web; using System.ServiceModel.Channels; using System.ServiceModel; namespace BlogSubmitterFXApp { public static class BingTranslate { public static string Translate(string clientId,string ClientSecret,string TextForTranslate) { AdmAccessToken admToken; string headerValue; //Get Client Id and Client Secret from https://datamarket.azure.com/developer/applications/ //Refer obtaining AccessToken (http://msdn.microsoft.com/en-us/library/hh454950.aspx) AdmAuthentication admAuth = new AdmAuthentication(clientId, ClientSecret); try { admToken = admAuth.GetAccessToken(); DateTime tokenReceived = DateTime.Now; // Create a header with the access_token property of the returned token headerValue = "Bearer " + admToken.access_token; return BingTranslate.TranslateMethod(headerValue, TextForTranslate); } catch (Exception ex) { return ex.Message; } } static string TranslateMethod(string authToken, string TextForTranslate) { // Add TranslatorService as a service reference, Address:http://api.microsofttranslator.com/V2/Soap.svc TranslatorService.LanguageServiceClient client = new TranslatorService.LanguageServiceClient(); //Set Authorization header before sending the request HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Method = "POST"; httpRequestProperty.Headers.Add("Authorization", authToken); // Creates a block within which an OperationContext object is in scope. using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) { OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; //string sourceText = "<UL><LI>Use generic class names. <LI>Use pixels to express measurements for padding and margins. <LI>Use percentages to specify font size and line height. <LI>Use either percentages or pixels to specify table and container width. <LI>When selecting font families, choose browser-independent alternatives. </LI></UL>"; string translationResult; //Keep appId parameter blank as we are sending access token in authorization header. translationResult = client.Translate("", TextForTranslate, "en", "ru", "text/html", "general"); return translationResult; } } } [DataContract] public class AdmAccessToken { [DataMember] public string access_token { get; set; } [DataMember] public string token_type { get; set; } [DataMember] public string expires_in { get; set; } [DataMember] public string scope { get; set; } } public class AdmAuthentication { public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; private string clientId; private string cientSecret; private string request; public AdmAuthentication(string clientId, string clientSecret) { this.clientId = clientId; this.cientSecret = clientSecret; //If clientid or client secret has special characters, encode before sending request this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret)); } public AdmAccessToken GetAccessToken() { return HttpPost(DatamarketAccessUri, this.request); } private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails) { //Prepare OAuth request WebRequest webRequest = WebRequest.Create(DatamarketAccessUri); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; byte[] bytes = Encoding.ASCII.GetBytes(requestDetails); webRequest.ContentLength = bytes.Length; using (Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } using (WebResponse webResponse = webRequest.GetResponse()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken)); //Get deserialized object from JSON stream AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); return token; } } } }
C# Post/Add BlogPost to wordpress
using CookComputing.XmlRpc; namespace BlogSubmitterFXApp.WorkWithAPI { public struct blogInfo { public string title; public string description; } public interface IgetCatList { [CookComputing.XmlRpc.XmlRpcMethod("metaWeblog.newPost")] string NewPage(int blogId, string strUserName, string strPassword, blogInfo content, int publish); } public static class WordPress { public static bool NewPost(string strUserName, string strPassword, string blogurl ,blogInfo bi) { blogInfo newBlogPost = default(blogInfo); newBlogPost.title = bi.title; newBlogPost.description = bi.description; IgetCatList categories = (IgetCatList)XmlRpcProxyGen.Create(typeof(IgetCatList)); XmlRpcClientProtocol clientProtocol = (XmlRpcClientProtocol)categories; //For example clientProtocol.Url = "http://msnetdeveloper.wordpress.com/xmlrpc.php"; clientProtocol.Url = blogurl; string result = null; result = ""; try { result = categories.NewPage(1, strUserName, strPassword, newBlogPost, 1); return false; } catch { return true; } } } }
Subscribe to:
Posts (Atom)