C# Обработываем событие на Hotkey в приложениях WPF

Способ 1

        public MainWindow()
        {
            InitializeComponent();
            AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
        }

        private void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
            {
                MessageBox.Show("CTRL + SHIFT + TAB trapped");
            }

            if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                MessageBox.Show("CTRL + TAB trapped");
            }
        }



Способ 2

<Window x:Class="WPFHotkey.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFHotkey"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="local:MainWindow.Some_Command" Executed="Some_Executed"/>
    </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Key="F4" Modifiers="ALT" Command="local:MainWindow.Some_Command"/>
    </Window.InputBindings>
    <Grid>
        
    </Grid>
</Window>


using System.Windows;
using System.Windows.Input;

namespace WPFHotkey
{
    
    public partial class MainWindow : Window
    {
        public static RoutedCommand Some_Command = new RoutedCommand();


        private void Some_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Hi!");
        }

        public MainWindow()
        {
            InitializeComponent();
        }

    }
}

c# проверяем xml по xsd схеме

using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

public class Sample {

  public static void Main() {

    XmlSchemaSet sc = new XmlSchemaSet();
    sc.Add("", "books.xsd");
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas = sc;
    settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
    XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings);
    while (reader.Read());

  }

  private static void ValidationCallBack(object sender, ValidationEventArgs e) {
    Console.WriteLine("Validation Error: {0}", e.Message);
  }
}

C# How to work with Excel. Simple example.


using Excel = Microsoft.Office.Interop.Excel; 
        
void CreateExcel()
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Excel.Application();//new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


            int i = 3;
            int j = 0;
            xlWorkSheet.Cells[1, 1] = "Protocol from " + DateTime.Now.ToShortDateString();
            Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 1];
            rg.EntireColumn.NumberFormat = "MM/DD/YYYY";

            xlWorkSheet.Columns.AutoFit();
                
            xlWorkBook.SaveAs("sdfgsdfg.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }

C# How to change UI control from other thread (WinForms and WPF)

WinForms:
public delegate void updateTextBoxDelegate(String textBoxString);  
public updateTextBoxDelegate updateTextBox; 

void updateTextBox1(string str ) { textBox1.Text = str1; } 

void display( string strItem ) 
{
         Form1.Invoke( Form1.updateTextBox, strItem ); 
}


WPF:
tempWindow.Dispatcher.BeginInvoke(new Action(delegate()
                    {
tempWindow.ChangeControlMethod();
                    }));

c# Перехватываем любое окно в Windows и вводим в него текст или прячем

Передаем какой то текст в окно,как будто вводим с клавиатуры и жмем ОК кнопкой Enter:
int iHandle = Common.NativeWin32.FindWindow(null, "Сюда пишем заголовок нужного окна");
Common.NativeWin32.SetForegroundWindow(iHandle);
System.Windows.Forms.SendKeys.SendWait("Здесь пишем текст который нужно ввести в это окно");
//Жмем в окне Enter   
System.Windows.Forms.SendKeys.SendWait("{ENTER}");

По аналогии прячем окно:
int iHandle = Common.NativeWin32.FindWindow(null, "Заголовок окна");
Common.NativeWin32.SetWindowPos(new IntPtr(iHandle), Common.NativeWin32.HWND.Top, 0, 0, 0, 0, Common.NativeWin32.SetWindowPosFlags.AsynchronousWindowPosition);

Вспомогательный класс:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace DeclTerminalApp.Common
{
    class NativeWin32
    {
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_CLOSE = 0xF060;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);

        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        static readonly IntPtr HWND_TOP = new IntPtr(0);
        static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

        /// <summary>
        /// Window handles (HWND) used for hWndInsertAfter
        /// </summary>
        public static class HWND
        {
            public static IntPtr
            NoTopMost = new IntPtr(-2),
            TopMost = new IntPtr(-1),
            Top = new IntPtr(0),
            Bottom = new IntPtr(1);
        }

        /// <summary>
        /// SetWindowPos Flags
        /// </summary>
        public static class SWP
        {
            public static readonly int
            NOSIZE = 0x0001,
            NOMOVE = 0x0002,
            NOZORDER = 0x0004,
            NOREDRAW = 0x0008,
            NOACTIVATE = 0x0010,
            DRAWFRAME = 0x0020,
            FRAMECHANGED = 0x0020,
            SHOWWINDOW = 0x0040,
            HIDEWINDOW = 0x0080,
            NOCOPYBITS = 0x0100,
            NOOWNERZORDER = 0x0200,
            NOREPOSITION = 0x0200,
            NOSENDCHANGING = 0x0400,
            DEFERERASE = 0x2000,
            ASYNCWINDOWPOS = 0x4000;
        }

        [Flags()]
        public enum SetWindowPosFlags : uint
        {
            /// <summary>If the calling thread and the thread that owns the window are attached to different input queues, 
            /// the system posts the request to the thread that owns the window. This prevents the calling thread from 
            /// blocking its execution while other threads process the request.</summary>
            /// <remarks>SWP_ASYNCWINDOWPOS</remarks>
            AsynchronousWindowPosition = 0x4000,
            /// <summary>Prevents generation of the WM_SYNCPAINT message.</summary>
            /// <remarks>SWP_DEFERERASE</remarks>
            DeferErase = 0x2000,
            /// <summary>Draws a frame (defined in the window's class description) around the window.</summary>
            /// <remarks>SWP_DRAWFRAME</remarks>
            DrawFrame = 0x0020,
            /// <summary>Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to 
            /// the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE 
            /// is sent only when the window's size is being changed.</summary>
            /// <remarks>SWP_FRAMECHANGED</remarks>
            FrameChanged = 0x0020,
            /// <summary>Hides the window.</summary>
            /// <remarks>SWP_HIDEWINDOW</remarks>
            HideWindow = 0x0080,
            /// <summary>Does not activate the window. If this flag is not set, the window is activated and moved to the 
            /// top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter 
            /// parameter).</summary>
            /// <remarks>SWP_NOACTIVATE</remarks>
            DoNotActivate = 0x0010,
            /// <summary>Discards the entire contents of the client area. If this flag is not specified, the valid 
            /// contents of the client area are saved and copied back into the client area after the window is sized or 
            /// repositioned.</summary>
            /// <remarks>SWP_NOCOPYBITS</remarks>
            DoNotCopyBits = 0x0100,
            /// <summary>Retains the current position (ignores X and Y parameters).</summary>
            /// <remarks>SWP_NOMOVE</remarks>
            IgnoreMove = 0x0002,
            /// <summary>Does not change the owner window's position in the Z order.</summary>
            /// <remarks>SWP_NOOWNERZORDER</remarks>
            DoNotChangeOwnerZOrder = 0x0200,
            /// <summary>Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to 
            /// the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent 
            /// window uncovered as a result of the window being moved. When this flag is set, the application must 
            /// explicitly invalidate or redraw any parts of the window and parent window that need redrawing.</summary>
            /// <remarks>SWP_NOREDRAW</remarks>
            DoNotRedraw = 0x0008,
            /// <summary>Same as the SWP_NOOWNERZORDER flag.</summary>
            /// <remarks>SWP_NOREPOSITION</remarks>
            DoNotReposition = 0x0200,
            /// <summary>Prevents the window from receiving the WM_WINDOWPOSCHANGING message.</summary>
            /// <remarks>SWP_NOSENDCHANGING</remarks>
            DoNotSendChangingEvent = 0x0400,
            /// <summary>Retains the current size (ignores the cx and cy parameters).</summary>
            /// <remarks>SWP_NOSIZE</remarks>
            IgnoreResize = 0x0001,
            /// <summary>Retains the current Z order (ignores the hWndInsertAfter parameter).</summary>
            /// <remarks>SWP_NOZORDER</remarks>
            IgnoreZOrder = 0x0004,
            /// <summary>Displays the window.</summary>
            /// <remarks>SWP_SHOWWINDOW</remarks>
            ShowWindow = 0x0040,
        }

        [DllImport("user32.dll")]
        public static extern int FindWindow(
            string lpClassName, // class name 
            string lpWindowName // window name 
        );

        [DllImport("user32.dll")]
        public static extern int SendMessage(
            int hWnd, // handle to destination window 
            uint Msg, // message 
            int wParam, // first message parameter 
            int lParam // second message parameter 
        );

        [DllImport("user32.dll")]
        public static extern int SetForegroundWindow(
            int hWnd // handle to window
            );

        private const int GWL_EXSTYLE = (-20);
        private const int WS_EX_TOOLWINDOW = 0x80;
        private const int WS_EX_APPWINDOW = 0x40000;
              
        public const int GW_HWNDFIRST = 0;
        public const int GW_HWNDLAST  = 1;
        public const int GW_HWNDNEXT  = 2;
        public const int GW_HWNDPREV  = 3;
        public const int GW_OWNER     = 4;
        public const int GW_CHILD     = 5;

        public delegate int EnumWindowsProcDelegate(int hWnd, int lParam);

        [DllImport("user32")]
        public static extern int EnumWindows(EnumWindowsProcDelegate lpEnumFunc, int lParam);

        [DllImport("User32.Dll")]
        public static extern void GetWindowText(int h, StringBuilder s, int nMaxCount);

        [DllImport("user32", EntryPoint = "GetWindowLongA")]
        public static extern int GetWindowLongPtr(int hwnd, int nIndex);

        [DllImport("user32")]
        public static extern int GetParent(int hwnd);

        [DllImport("user32")]
        public static extern int GetWindow(int hwnd, int wCmd);

        [DllImport("user32")]
        public static extern int IsWindowVisible(int hwnd);

        [DllImport("user32")]
        public static extern int GetDesktopWindow();
    }
}

c# Вставляем флэшку в компьютер и обрабатываем это событие


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# Пишем аналог КриптоАРМ Подписать и зашифровать с архивированием перед шифрованием.

Для создания 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;
            }
        }
    }
}

c# read rss


using System;
using System.Collections.Generic;
using System.Xml;
using System.ServiceModel.Syndication;

namespace LJUpper
{
    public static class RSS
    {
        public struct RssItem
        {
            public string Title { get; set; }
            public string Text { get; set; }
        }

        public static List<RssItem> GetRSS(string _feedUri)
        {
            SyndicationFeed syndicationFeed;
            List<RssItem> resList = new List<RssItem>();
            try
            {
                using (XmlReader reader = XmlReader.Create(new Uri(_feedUri).AbsoluteUri))
                    syndicationFeed = SyndicationFeed.Load(reader);

                string _title = "";
                string _text = "";


                foreach (SyndicationItem t in syndicationFeed.Items)
                {
                    if (t.Title == null)
                        _title += t.Title.Text;
                    if (t.Content == null)
                        _text += t.Summary.Text;
                    else
                        _text += (t.Content as TextSyndicationContent).Text;
                    resList.Add(new RssItem() { Title = t.Title.Text, Text = _text });
                }
            }
            catch
            {
                return null;
            }
            return resList;
        }
    }
}

C# Post/Add BlogPost Blogger.com

Download GData.Client https://code.google.com/p/google-gdata/downloads/list



using System;
using Google.GData.Client;

namespace BloggerAPI
{
    public static class Blogger
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="UserblogTitle">If null,then will select first user blog</param>
        public static bool SubmitNewPost(string username, string password, string UserblogTitle)
        {
            Service service = new Service("blogger", "blogger-example");
            service.Credentials = new GDataCredentials(username, password);
            try
            {
                Uri blogPostUri = SelectUserBlog(service, UserblogTitle);
                AtomEntry createdEntry = PostNewEntry(service, blogPostUri);
                return true;
            }
            catch
            {
                return false;
            }
        }

        static AtomEntry PostNewEntry(Service service, Uri blogPostUri)
        {
            AtomEntry createdEntry = null;
            if (blogPostUri != null)
            {
                AtomEntry newPost = new AtomEntry();
                newPost.Title.Text = "Marriage!";
                newPost.Content = new AtomContent();
                newPost.Content.Content = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" +
                    "<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
                    "<p>He is the last man on earth I would ever desire to marry.</p>" +
                    "<p>Whatever shall I do?</p>" +
                    "</div>";
                newPost.Content.Type = "xhtml";
                createdEntry = service.Insert(blogPostUri, newPost);
            }
            return createdEntry;
        }

        static Uri SelectUserBlog(Service service, string UserblogTitle)
        {
            FeedQuery query = new FeedQuery();
            query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
            AtomFeed feed = service.Query(query);
            Uri blogPostUri = null;
            if (feed != null)
                foreach (AtomEntry entry in feed.Entries)
                    if (UserblogTitle == entry.Title.Text || UserblogTitle == null)
                    {
                        for (int i = 0; i < entry.Links.Count; i++)
                            if (entry.Links[i].Rel.Equals("http://schemas.google.com/g/2005#post"))
                                blogPostUri = new Uri(entry.Links[i].HRef.ToString());
                        return blogPostUri;
                    }
            return blogPostUri;
        }
    }
}

C# Post/Add BlogPost to LiveJournal.com Using


public struct blogInfo
{
        public string title;
        public string description;
}

public static class LJ
    {
        public static string NewPost(string strUserName, string strPassword, blogInfo bi)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.livejournal.com/interface/xmlrpc");
            request.Method = "POST";

            string command = String.Format(
            @"<?xml version=""1.0""?><methodCall><methodName>LJ.XMLRPC.postevent</methodName><params><param><value><struct>
                <member><name>username</name>
                    <value><string>{0}</string></value>
                    </member>
                    <member><name>password</name>
                    <value><string>{1}</string></value>
                    </member>
                    <member><name>event</name>
                    <value><string>{3}
                    </string></value>
                    </member>
                    <member><name>subject</name>
                    <value><string>{2}</string></value>
                    </member>
                    <member><name>lineendings</name>
                    <value><string>pc</string></value>
                    </member>
                    <member><name>year</name>
                    <value><int>"+DateTime.Now.Year.ToString()+@"</int></value>
                    </member>
                    <member><name>mon</name>
                    <value><int>" + DateTime.Now.Month.ToString() + @"</int></value>
                    </member>
                    <member><name>day</name>
                    <value><int>" + DateTime.Now.Day.ToString() + @"</int></value>
                    </member>
                    <member><name>hour</name>
                    <value><int>" + DateTime.Now.Hour.ToString() + @"</int></value>
                    </member>
                    <member><name>min</name>
                    <value><int>" + DateTime.Now.Minute.ToString() + @"</int></value>
                    </member>
                    </struct></value>
                    </param>
                    </params>
                    </methodCall>", strUserName, strPassword, bi.title,bi.description);

            byte[] bytes = Encoding.ASCII.GetBytes(command);
            request.ContentLength = bytes.Length;
            using (var stream = request.GetRequestStream())
                stream.Write(bytes, 0, bytes.Length);

            using (var stream = new StreamReader(request.GetResponse().GetResponseStream()))
                return stream.ReadToEnd();

        }
    }

MSSQL UPDATE DATETIME

UPDATE [mytablename] set [date_to]=CAST('2013-16-04' AS DATETIME) where [number_rec]='0005814'

C# Локализация Windows 8 приложений


Введение

Шаблоны Windows Phone 8 проектов теперь включают в себя поддержку локализаций приложений. Что такое локализация? Когда вы разрабатываете приложение Windows Phone app, часто вам необходимо это делать сразу  для нескольких регионов и соответственно нескольких языков, простыми словами вам необходимо перевести интерфейс или какую то графическую часть. 

Давайте создадим Windows Phone 8 приложение и на примере посмотрим как локализовать его.

Первым делом нам вам необходимо выбрать "Windows Phone OS 8.0" платформу когда создаете свое приложение.

Step 1: Создадим новое Windows Phone 8 приложение с целевой платформой версии 8.0.

Как я говорил локализация доступна для восьмой версии платформы; она не поддерживается в версии 7.1, вы можете увидеть различия между версиями на картинке ниже, когда вы создаете Windows Phone 8.0 приложение файл ресурсов находится в папке "Resources" для каждой поддерживаемой локализации и создается класс "LocalizedStrings", также используется привязка с помощью XAML.

windowsphone8-localization1.gif

По умолчанию запись, относящаяся к  классу помощнику "LocalizedStrings" создается в файле App.xaml.

windowsphone8-localization2.gif

Шаг 2: Теперь давайте привяжем заголовок приложения к свойству из global resource.
 
<!--TitlePanel contains the name of the application and page title-->
 
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
 
     <TextBlock Text="{Binding Path=LocalizedResources.ApplicationTitle}" 
                 
 Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
 
     <TextBlock Text="{Binding Path=LocalizedResources.MainPageTitle}" Margin="9,-7,0,0"
 
                 Style="{StaticResource PhoneTextTitle1Style}"/>
 
</StackPanel>

Посмотрим на функцию 
 InitializeLanguage():

windowsphone8-localization3.gif

Шаг 3: Добавим определенную локализацию приложения.

Зайдите в свойства проекта и там вы можете выбрать язык который желаете использовать.

windowsphone8-localization4.gif

После добавления новых языков создадутся соответствующие файлы ресурсов и добавятся в папку Resources.

windowsphone8-localization5.gif

Все файлы ресурсов содержат все детали локализации, чтобы их посмотреть нам не обязательно запускать приложение.

Когда вы откроете файл Resources.resx вы увидите ApplicationTitle на разных языках.

windowsphone8-localization6a.gif

windowsphone8-localization7a.gif

Step 4: Протестируем наше приложением просто запустив эмулятор и мы увидим ApplicationTitle на главной странице по умолчанию.

windowsphone8-localization13.gif

Теперь давайте протестируем нашу новую локализацию.

Для изменения языка используйте следующий порядок действий.

Шаг 1: Нажмите кнопку Start, потом нажмите на иконку стрелку.

windowsphone8-localization8.gif

Шаг 2: Выберите настройки из списка и нажмите на region & language.

windowsphone8-localization9.gif

windowsphone8-localization10.gif

Шаг 3: Выберите язык который вы добавили. Мы добавили немецкий так что выберем его.

windowsphone8-localization11.gif

windowsphone8-localization12.gif
Шаг 4: Нажмите чтобы подтвердить изменения и перезагрузите телефон.

windowsphone8-localization15.gif

Эмулятор изменит настройки и вернет стартовое окно.

Теперь запустите своё приложение и вы увидите переведенный UI.

windowsphone8-localization14.gif