четверг, 31 мая 2012 г.

Get special folders icons (images) using C#




public class SpecialFolderIconSample      
{
 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SHGetFileInfo(IntPtr pszPath, uint dwFileAttributes, out SHFILEINFO psfi, uint cbFileInfo, int uFlags);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DestroyIcon(IntPtr hIcon);

        [DllImport("shell32.dll", SetLastError = true)]
        private static extern int SHGetSpecialFolderLocation(IntPtr hwndOwner, CSIDL nFolder, ref IntPtr ppidl);

        [DllImport("shell32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SHGetPathFromIDListW(IntPtr pidl, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszPath);

        private enum CSIDL
        {
            CSIDL_DESKTOP = 0x0000,    // <desktop>
            CSIDL_INTERNET = 0x0001,    // Internet Explorer (icon on desktop)
            CSIDL_PROGRAMS = 0x0002,    // Start Menu\Programs
            CSIDL_CONTROLS = 0x0003,    // My Computer\Control Panel
            CSIDL_PRINTERS = 0x0004,    // My Computer\Printers
            CSIDL_PERSONAL = 0x0005,    // My Documents
            CSIDL_FAVORITES = 0x0006,    // <user name>\Favorites
            CSIDL_STARTUP = 0x0007,    // Start Menu\Programs\Startup
            CSIDL_RECENT = 0x0008,    // <user name>\Recent
            CSIDL_SENDTO = 0x0009,    // <user name>\SendTo
            CSIDL_BITBUCKET = 0x000a,    // <desktop>\Recycle Bin
            CSIDL_STARTMENU = 0x000b,    // <user name>\Start Menu
            CSIDL_MYDOCUMENTS = 0x000c,    // logical "My Documents" desktop icon
            CSIDL_MYMUSIC = 0x000d,    // "My Music" folder
            CSIDL_MYVIDEO = 0x000e,    // "My Videos" folder
            CSIDL_DESKTOPDIRECTORY = 0x0010,    // <user name>\Desktop
            CSIDL_DRIVES = 0x0011,    // My Computer
            CSIDL_NETWORK = 0x0012,    // Network Neighborhood (My Network Places)
            CSIDL_NETHOOD = 0x0013,    // <user name>\nethood
            CSIDL_FONTS = 0x0014,    // windows\fonts
            CSIDL_TEMPLATES = 0x0015,
            CSIDL_COMMON_STARTMENU = 0x0016,    // All Users\Start Menu
            CSIDL_COMMON_PROGRAMS = 0X0017,    // All Users\Start Menu\Programs
            CSIDL_COMMON_STARTUP = 0x0018,    // All Users\Startup
            CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019,    // All Users\Desktop
            CSIDL_APPDATA = 0x001a,    // <user name>\Application Data
            CSIDL_PRINTHOOD = 0x001b,    // <user name>\PrintHood
            CSIDL_LOCAL_APPDATA = 0x001c,    // <user name>\Local Settings\Applicaiton Data (non roaming)
            CSIDL_ALTSTARTUP = 0x001d,    // non localized startup
            CSIDL_COMMON_ALTSTARTUP = 0x001e,    // non localized common startup
            CSIDL_COMMON_FAVORITES = 0x001f,
            CSIDL_INTERNET_CACHE = 0x0020,
            CSIDL_COOKIES = 0x0021,
            CSIDL_HISTORY = 0x0022,
            CSIDL_COMMON_APPDATA = 0x0023,    // All Users\Application Data
            CSIDL_WINDOWS = 0x0024,    // GetWindowsDirectory()
            CSIDL_SYSTEM = 0x0025,    // GetSystemDirectory()
            CSIDL_PROGRAM_FILES = 0x0026,    // C:\Program Files
            CSIDL_MYPICTURES = 0x0027,    // C:\Program Files\My Pictures
            CSIDL_PROFILE = 0x0028,    // USERPROFILE
            CSIDL_SYSTEMX86 = 0x0029,    // x86 system directory on RISC
            CSIDL_PROGRAM_FILESX86 = 0x002a,    // x86 C:\Program Files on RISC
            CSIDL_PROGRAM_FILES_COMMON = 0x002b,    // C:\Program Files\Common
            CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c,    // x86 Program Files\Common on RISC
            CSIDL_COMMON_TEMPLATES = 0x002d,    // All Users\Templates
            CSIDL_COMMON_DOCUMENTS = 0x002e,    // All Users\Documents
            CSIDL_COMMON_ADMINTOOLS = 0x002f,    // All Users\Start Menu\Programs\Administrative Tools
            CSIDL_ADMINTOOLS = 0x0030,    // <user name>\Start Menu\Programs\Administrative Tools
            CSIDL_CONNECTIONS = 0x0031,    // Network and Dial-up Connections
            CSIDL_COMMON_MUSIC = 0x0035,    // All Users\My Music
            CSIDL_COMMON_PICTURES = 0x0036,    // All Users\My Pictures
            CSIDL_COMMON_VIDEO = 0x0037,    // All Users\My Video
            CSIDL_CDBURN_AREA = 0x003b    // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
        }

        private BitmapImage GetFolderIcon(CSIDL csidl)
        {
            var shfi = new SHFILEINFO();

            IntPtr ptrDir = IntPtr.Zero;
            SHGetSpecialFolderLocation(IntPtr.Zero, csidl, ref ptrDir);

            var res = SHGetFileInfo(ptrDir, 0, out shfi, (uint)Marshal.SizeOf(shfi), 0x000000100 | 0x000000008);

            Marshal.FreeCoTaskMem(ptrDir);


            var icon = (Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

            DestroyIcon(shfi.hIcon);

            Bitmap bmp = icon.ToBitmap();

            using (MemoryStream strm = new MemoryStream())
            {
                bmp.Save(strm, System.Drawing.Imaging.ImageFormat.Png);

                BitmapImage bmpImage = new BitmapImage();

                bmpImage.BeginInit();
                bmpImage.CacheOption = BitmapCacheOption.OnLoad;
                strm.Seek(0, SeekOrigin.Begin);
                bmpImage.StreamSource = strm;
                bmpImage.EndInit();

                bmpImage.Freeze();

                return bmpImage;
            }
        }

        private string GetFolderPath(CSIDL csidl)
        {
            IntPtr ptrDir = IntPtr.Zero;

            try
            {
                const int MAX_PATH = 260;

                SHGetSpecialFolderLocation(IntPtr.Zero, csidl, ref ptrDir);

                StringBuilder sbDirVideo = new StringBuilder(MAX_PATH);

                if (SHGetPathFromIDListW(ptrDir, sbDirVideo))
                {
                    return sbDirVideo.ToString();
                }
            }
            finally
            {
                Marshal.FreeCoTaskMem(ptrDir);
            }

            return null;
        }

public void LoopSpecialFolders()
{
foreach (var specialFolder in Enum.GetNames(typeof(CSIDL)).OrderBy(f => f))

            {
                var f = specialFolder;

                var sfi = new SystemFolderInfo
                    {
                        FolderName = f.Substring(f.IndexOf("_") + 1),
                        Path = GetFolderPath((CSIDL)Enum.Parse(typeof(CSIDL), f)),
                        Icon = GetFolderIcon((CSIDL)Enum.Parse(typeof(CSIDL), f))
                    };
            }

}
}


ListView autogenerate columns and sort on header click wpf mvvm

In XAML:

<ViewModel:ListViewEx IsSortable="True" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"  AutoGenerateColumns="True" />


using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media.Imaging;



public class ListViewEx : ListView
    {
        public bool AutoGenerateColumns
        {
            get { return (bool)GetValue(AutoGenerateColumnsProperty); }
            set { SetValue(AutoGenerateColumnsProperty, value); }
        }

        public bool IsSortable
        {
            get { return (bool)GetValue(IsSortableProperty); }
            set { SetValue(IsSortableProperty, value); }
        }

        public static readonly DependencyProperty AutoGenerateColumnsProperty =
            DependencyProperty.Register("AutoGenerateColumns", typeof(bool), typeof(ListViewEx), new PropertyMetadata(false));

        public static readonly DependencyProperty IsSortableProperty =
            DependencyProperty.Register("IsSortable", typeof(Boolean), typeof(ListViewEx), new PropertyMetadata(false, OnRegisterSortableGrid));

        protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
        {
            base.OnItemsSourceChanged(oldValue, newValue);

            if (AutoGenerateColumns)
            {
                GridView gridView = new GridView();

                Type sourceItemType = ItemsSource.AsQueryable().ElementType;
                PropertyInfo[] properties = sourceItemType.GetProperties();

                foreach (var prop in properties)
                {
                    GridViewColumn column = new GridViewColumn();

                    if (prop.PropertyType == typeof(BitmapImage))
                    {
                        DataTemplate template = new DataTemplate();

                        FrameworkElementFactory childFactory = new FrameworkElementFactory(typeof(System.Windows.Controls.Image));

                        childFactory.SetBinding(System.Windows.Controls.Image.SourceProperty, new Binding(prop.Name));
                        childFactory.SetValue(WidthProperty, 16.0);
                        template.VisualTree = childFactory;

                        column.CellTemplate = template;
                    }
                    else
                    {
                        column.Header = (prop.GetCustomAttributes(typeof(DescriptionAttribute), false).First() as DescriptionAttribute).Description;
                        column.DisplayMemberBinding = new Binding(prop.Name);
                        column.Width = double.NaN;
                    }

                    gridView.Columns.Add(column);
                }

                View = gridView;
            }
        }


        private static GridViewColumnHeader _lastHeaderClicked;
        private static ListSortDirection _lastDirection;
        private static ListView _listView;

        private static void OnRegisterSortableGrid(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            ListView grid = obj as ListView;

            if (grid != null)
            {
                _listView = obj as ListView;
                grid.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickedHandler));
            }
        }

        private static void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;

            if (headerClicked != null)
            {
                ListSortDirection direction;

                if (headerClicked != _lastHeaderClicked)
                {
                    direction = ListSortDirection.Ascending;
                }
                else
                {
                    direction = _lastDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
                }

                if (headerClicked.Column.DisplayMemberBinding != null)
                {
                    Sort((headerClicked.Column.DisplayMemberBinding as Binding).Path.Path, direction);

                    _lastHeaderClicked = headerClicked;
                    _lastDirection = direction;
                }
            }
        }

        private static void Sort(string propertyName, ListSortDirection direction)
        {
            var view = (ListCollectionView)CollectionViewSource.GetDefaultView(_listView.ItemsSource);

            if (view != null)
            {
                try
                {
                    view.CustomSort = new ListViewComparer { PropertyName = propertyName, SortDirection = direction };
                    _listView.Items.Refresh();
                }
                catch (Exception)
                {
                }
            }
        }
    }


 public class ListViewComparer : IComparer
    {
        public string PropertyName { get; set; }

        public ListSortDirection SortDirection { get; set; }

        public int Compare(object x, object y)
        {
            try
            {
                int result = 0;

                var pro1 = x.GetType().GetProperty(PropertyName);
                var pro2 = y.GetType().GetProperty(PropertyName);

                var valx = pro1.GetValue(x, null);
                var valy = pro2.GetValue(y, null);

                if (valx == null && valy == null) return 0;
                if (valx == null) return -1;
                if (valy == null) return 1;

                var type = pro1.PropertyType;

                if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    type = Nullable.GetUnderlyingType(type);
                }

                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.String:
                    case TypeCode.Boolean:
                        result = valx.ToString().CompareTo(valy.ToString());
                        break;
                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.Decimal:
                        result = Convert.ToDouble(valx).CompareTo(Convert.ToDouble(valy));
                        break;
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.Int32:
                    case TypeCode.Int64:
                        result = Convert.ToInt64(valx).CompareTo(Convert.ToInt64(valy));
                        break;
                    case TypeCode.UInt16:
                    case TypeCode.UInt32:
                    case TypeCode.UInt64:
                        result = Convert.ToUInt64(valx).CompareTo(Convert.ToUInt64(valy));
                        break;
                    case TypeCode.DateTime:
                        result = Convert.ToDateTime(valx).CompareTo(Convert.ToDateTime(valy));
                        break;
                }

                if (SortDirection == ListSortDirection.Descending) result *= -1;

                return result;
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }



четверг, 24 мая 2012 г.

Set docx header using ooxml sdk C#


 foreach (var headerPart in mainDocumentPart.HeaderParts)
                {
                    foreach (var text in headerPart.Header.Descendants<Text>())
                    {
                        if (text.Text.Contains("approveNumber"))
                        {

                            text.Text = "newHeader";
                            headerPart.Header.Save();
                            break;
                        }
                    }
                }

Англо-русский словарь заимствованных слов (English-Russian loanwords dictionary)



1. Compose - составлять (композиция)
2. Assistance - помощь, содействие (асистент)
3. Meet - встречаться (митинг)
4. Repeat - повторять (репетиция)
5. Plenty -изобилие, множество (плантация)
6. Opposit - напротив (оппозиция)
7. Merchant - торговец (мерчандайзинг)
8. Fancy - фантастический, причудливый (фантастика)
9. Temper - характер (темперамент)
10. Patient - терпеливый, страдающий (пациент)
11. Vine - виноградная лоза (вино)
12. Grace - изящество (грация)
13. Insult - оскорбление, обида, кровоизлияние (инсульт)
14. Rosy - розовый, румяный, цветущий (роза)
15. Fury - неистовство, ярость (Фурия - богиня мести)
16. Spindle - веретено (шпиндель)
17. Accident - авария, катастрофа, проишествие (инцидент)
18. Cheat - мошенник (читер)
19. Rent - сдавать в аренду (рента)
20. Breif - короткий (брифинг)
21. Purge - очищать, освобождать (Пурген)
22. Grab - хватать (грабитель)
23. Attract - привлекать (аттракцион)
24. Barrel - бочка (баррель нефти)
25. Folk - народ, народный (фольклор)
26. Kick - удар, толчок (лоу кик, кикбоксёр )
27. Stick -приклеивать, наклеивать (стикер)
28. Bandage - бинт (бандаж)
29. Rerely - редко (раритетный)
30. Pinch - ущипнуть (пинцет)
31. Loyal -  верный (лояльный)
32. Argue - спорить, убеждать (аргумент)
33. Deal -  сделка (диллер)
34. Sole - единственный (соло)
35. Substitute - заменять (товар- субститут)
36. Investigate - исследовать (инвестиции)
37. Memory - память (мемуары)
38.Cannon - пушка (канонада)
39. Pill -таблетка (пилюля)
40. Ruin - разрушать (руины)
41. Infant - младенец (инфантильный)
42. Dive - нырять (дайвинг)
43. Discont - скидка (дисконтная карта)
44. Heel - пятка (Ахилес)
45. Feminine - женский (феминистки)
46. Provide - обеспечивать (интернет-провайдер)
47. Produce - выпускать (музыкальный продюсер)
48.Penalty - штраф (пенальти в футболе)
49. Promote - продвигать (промоутеры товаров)
50. Violin - скрипка (виолончель)
51.Van - фургон (минивэн)
52. Leg - нога (леггенсы)

среда, 23 мая 2012 г.

Split (merge) table cell docx using ooxml sdk C# with the same text

var tables = mainDocumentPart.Document.Body.Elements<Table>().ToList();


var rows = tables[1].Elements<TableRow>().ToArray();

            var wasRestart = false;

            for (int i = 0; i < rows.Length - 1; i++)
            {
                if (rows[i].Elements<TableCell>().ElementAt(1).Elements<Paragraph>().First().Elements<Run>().First().Elements<Text>().First().Text ==
                   rows[i + 1].Elements<TableCell>().ElementAt(1).Elements<Paragraph>().First().Elements<Run>().First().Elements<Text>().First().Text)
                {
                    rows[i].Elements<TableCell>().ElementAt(1).TableCellProperties.VerticalMerge = new VerticalMerge() { Val = wasRestart ? MergedCellValues.Continue : MergedCellValues.Restart };
                    rows[i + 1].Elements<TableCell>().ElementAt(1).TableCellProperties.VerticalMerge = new VerticalMerge();

                    rows[i].Elements<TableCell>().ElementAt(4).TableCellProperties.VerticalMerge = new VerticalMerge() { Val = wasRestart ? MergedCellValues.Continue : MergedCellValues.Restart };
                    rows[i + 1].Elements<TableCell>().ElementAt(4).TableCellProperties.VerticalMerge = new VerticalMerge();

                    wasRestart = true;
                }
                else
                {
                    wasRestart = false;
                }
            }

суббота, 12 мая 2012 г.

Merge docx files using C# OOXML SDK WordprocessingDocument class

This code create one docx document from template replacing certain fields in template.


 class DocumentInfo
    {
        public string ProductName { get; set; }

        public string AWPCount { get; set; }

        public string RegNumber { get; set; }

        public string OrganizationName { get; set; }

        public string LifeTime { get; set; }
    }


public static byte[] GetDocx(string templatePath, DocumentInfo[] documentInfos)
        {
            if (documentInfos.Length == 0)
            {
                throw new Exception("documentInfos count = 0!");
            }

            if (!File.Exists(templatePath))
            {
                throw new FileNotFoundException("Document template not found", templatePath);
            }

            var template = File.ReadAllBytes(templatePath);

            var mainStream = new MemoryStream();

            mainStream.Write(template, 0, template.Length);
            mainStream.Position = 0;

            byte[] result;
            try
            {
                using (var mainDocument = WordprocessingDocument.Open(mainStream, true))
                {
                    var mainXml = mainDocument.MainDocumentPart.Document.Body.OuterXml;

                    mainXml = mainXml.Replace("productName", documentInfos[0].ProductName);
                    mainXml = mainXml.Replace("AWPCount", documentInfos[0].AWPCount);
                    mainXml = mainXml.Replace("regNumber", documentInfos[0].RegNumber);
                    mainXml = mainXml.Replace("organizationName", documentInfos[0].OrganizationName);
                    mainXml = mainXml.Replace("lifeTime", documentInfos[0].LifeTime);

                    var mainBody = XElement.Parse(mainXml);

                    for (var i = 1; i < documentInfos.Length; i++)
                    {
                        using (var tempDocument = WordprocessingDocument.Open(new MemoryStream(template), false))
                        {
                            var tempXml = tempDocument.MainDocumentPart.Document.Body.OuterXml;

                            tempXml = tempXml.Replace("productName", documentInfos[i].ProductName);
                            tempXml = tempXml.Replace("AWPCount", documentInfos[i].AWPCount);
                            tempXml = tempXml.Replace("regNumber", documentInfos[i].RegNumber);
                            tempXml = tempXml.Replace("organizationName", documentInfos[i].OrganizationName);
                            tempXml = tempXml.Replace("lifeTime", documentInfos[i].LifeTime);

                            var tempBody = XElement.Parse(tempXml);

                            mainBody.Add(tempBody);
                            mainDocument.MainDocumentPart.Document.Body = new Body(mainBody.ToString());
                            mainDocument.MainDocumentPart.Document.Save();
                            mainDocument.Package.Flush();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format(CultureInfo.CurrentCulture, "Error while merging files.{0", 1), e);
            }
            finally
            {
                result = mainStream.ToArray();
                mainStream.Close();
                mainStream.Dispose();
            }

            return result;
        }

вторник, 24 апреля 2012 г.

Get share folder effective rights using C#


 class NetDirectorySecurity : NativeObjectSecurity
    {
        public NetDirectorySecurity(string ResName, AccessControlSections IncludeSections)
            : base(true, ResourceType.LMShare, ResName, IncludeSections)
        {
        }

        private static FileSystemRights RightsFromAccessMask(int accessMask)
        {
            return (FileSystemRights)accessMask;
        }

        public sealed override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask,
            bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
        {
            return new FileSystemAccessRule(identityReference, RightsFromAccessMask(accessMask), inheritanceFlags, propagationFlags, type);
        }

        public sealed override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask,
            bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
        {
            return new FileSystemAuditRule(identityReference, RightsFromAccessMask(accessMask), inheritanceFlags, propagationFlags, flags);
        }

        public override Type AccessRightType { get { return typeof(FileSystemRights); } }
        public override Type AccessRuleType { get { return typeof(FileSystemAccessRule); } }
        public override Type AuditRuleType { get { return typeof(FileSystemAuditRule); } }
    } 


                        NetDirectorySecurity nds = new NetDirectorySecurity(sharedName, AccessControlSections.Access);
                     
                        var permissions = nds.GetAccessRules(true, true, typeof(SecurityIdentifier));
                        FileSystemRights denyRights = 0;
                        FileSystemRights allowRights = 0;

                        var accessRules = permissions.Cast<FileSystemAccessRule>().Where(ar => ar.IdentityReference.Value == sid).ToList();

                        if (accessRules.Count == 0) mask = 0;

                        foreach (var accessRule in accessRules)
                        {
                            if (accessRule.AccessControlType == AccessControlType.Deny)
                            {
                                denyRights |= accessRule.FileSystemRights;
                            }
                            else
                            {
                                allowRights |= accessRule.FileSystemRights;
                            }
                        }

                        var mask = (int)((allowRights | denyRights) ^ denyRights);