giovedì 26 giugno 2014

Export a list items in an excel file.

c# .NET 4.0 (WPF) - Excel 2013

I would like to export my list items (WPF ListView) in an excel file and I would like to do this using a generic mode.

I did it in this way:

        /// <summary>
        /// Exports to CSV.
        /// </summary>
        private void ExportToCsv()
        {
            string exportPath = ConfigurationManager.AppSettings["ExportToCsvPath"];
            if (!Directory.Exists(exportPath))
                Directory.CreateDirectory(exportPath);

            string fileName = Path.Combine(exportPath, "ExportActivities.csv");

            if (!Help.ExportToCsvStream(CreateDataGrid(), fileName))
            {
                string msg = String.Format(Strings.def_msgExportToCsvError, Environment.NewLine);
                MessageBox.Show(msg, MessageTitle, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// Creates the data grid.
        /// </summary>
        /// <returns></returns>
        private StringBuilder CreateDataGrid()
        {
            try
            {
                // These are the column headers of the excel file.
                String[] headersToExport =
                {
                    "UserName", "Municipality", "BinderName", "BoxNumber", "ImageNumber", "DiscardedImage",
                    "DocumentsNumber", "TotalPagesNumber", "StartDate", "EndDate", "SendDate", "ImportDate", "State"
                };

                // These are columns of the excel file and these are the properties that I want to export.
                String[] propertiesToExport =
                {
                    "PreferedUser.UserName", "Municipality", "BinderName", "BoxNumber", "ImageNumber", "DiscardedImage",
                    "DocumentsNumber", "TotalPagesNumber", "StartDate", "EndDate", "SendDate", "ImportDate", "State"
                };

                return Activities.ToCsv(headersToExport, propertiesToExport);
            }
            catch (Exception ex)
            {
                string msg = String.Format(Strings.def_msgExportToCsvError, Environment.NewLine);
                MessageBox.Show(msg, MessageTitle, MessageBoxButton.OK, MessageBoxImage.Error);

                Log.WriteLog(ex);
                return null;
            }
        }

        /// <summary>
        /// Exports to CSV stream.
        /// </summary>
        /// <param name="sb">The sb.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static bool ExportToCsvStream(StringBuilder sb, string fileName)
        {
            try
            {
                // Default ANSI code for csv file
                Encoding ansi = Encoding.GetEncoding(1252);
                byte[] csvBytes = ansi.GetBytes(sb.ToString());
               
                CreateAndOpenFile(csvBytes, fileName);

                return true;
            }
            catch (Exception ex)
            {               
                Log.WriteLog(ex);
                return false;
            }
        }

        /// <summary>
        /// Formats for CSV.
        /// </summary>
        /// <param name="dato">The dato.</param>
        /// <returns></returns>
        public static string FormatForCsv(string dato)
        {
            if (dato != null)
            {
                string datoFormatted = dato.Trim();

                if (string.IsNullOrEmpty(datoFormatted))
                    return string.Empty;

                datoFormatted =
                    datoFormatted
                        .Replace(Environment.NewLine, string.Empty)
                        .Replace(@"""", "'")
                        .Replace(";", ".");
               
                if (datoFormatted.Length > 255)
                    datoFormatted = datoFormatted.Substring(0, 255);

                return string.Format(@"=""{0}""", datoFormatted);
            }
            return string.Empty;
        }

        private static int _processIdExcel;
        /// <summary>
        /// Creates the and open file.
        /// </summary>
        /// <param name="bytes">The bytes.</param>
        /// <param name="filename">The filename.</param>
        private static void CreateAndOpenFile(byte[] bytes, string filename)
        {
            try
            {
                if (File.Exists(filename))
                {
                    CloseExcel();
                    File.Delete(filename);
                }

                using (var stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                {
                    stream.Write(bytes, 0, bytes.Length);
                }

                var process = Process.Start(filename);
                if (process != null) _processIdExcel = process.Id;
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                throw;
            }
        }

        /// <summary>
        /// Closes the excel.
        /// </summary>
        private static void CloseExcel()
        {
            try
            {
                if (_processIdExcel > 0)
                {
                    // The Excel process already exists and has been instantiated from us.
                    Process procExcel = Process.GetProcessById(_processIdExcel);
                    if (String.Equals(procExcel.ProcessName, "excel", StringComparison.OrdinalIgnoreCase))
                        procExcel.Kill();

                    _processIdExcel = 0;
                }
                else
                {
                    // The process has been instantiated but Excel does not check if there is anyway existence.
                    Process[] processes = Process.GetProcessesByName("Excel");
                    if (processes.Length > 0)
                    {
                        _processIdExcel = processes[0].Id;
                        CloseExcel();
                    }
                }
                Thread.Sleep(20);
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
            }
        }

        /// <summary>
        /// Gets or sets the activities.
        /// </summary>
        /// <value>
        /// The activities.
        /// </value>
        public ObservableCollection<Activity> Activities
        {
            get { return _activities; }
            set
            {
                if (value != _activities)
                {
                    _activities = value;
                    RaisePropertyChanged(ActivitiesPropertyName);
                }
            }
        }

        /// <summary>
        /// To the CSV.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumerableList">The enumerable list.</param>
        /// <param name="headersToExport">The headers to export.</param>
        /// <param name="propertiesToExport">The properties to export.</param>
        /// <returns></returns>
        public static StringBuilder ToCsv<T>(this IEnumerable<T> enumerableList, String[] headersToExport,
            String[] propertiesToExport)
        {
            try
            {
                if (enumerableList != null)
                {
                    // Create the CSV file to which grid data will be exported.
                    var sb = new StringBuilder();
                    var typeParameterType = typeof (T);

                    #region Headers

                    foreach (string t in headersToExport)
                        sb.Append(String.Concat(t, ";"));

                    sb.Append(Environment.NewLine);

                    #endregion

                    #region Properties

                    var propertyInfos = typeParameterType.GetProperties();
                    foreach (var entity in enumerableList)
                    {
                        for (int index = 0; index < propertiesToExport.Length; index++)
                        {
                            String[] properties = propertiesToExport[index].Split(".".ToCharArray());

                            PropertyInfo property = null;
                            if (properties.Count() > 1)
                            {
                                #region If it is a composed property, like PreferedUser.UserName

                                var pInfos = propertyInfos;
                                object en = entity;

                                for (int i = 0; i < properties.Count(); i++)
                                {
                                    property = pInfos.FirstOrDefault(pi => pi.Name.Equals(properties[i]));

                                    if (property != null && en != null && i < properties.Count() - 1)
                                    {
                                        pInfos = property.PropertyType.GetProperties();
                                        en = property.GetValue(en, null);
                                    }
                                }

                                if (en != null)
                                {
                                    if (property != null && property.PropertyType == typeof (DateTime?))
                                    {
                                        if (property.GetValue(en, null) != null)
                                            sb.Append(
                                                String.Concat(
                                                    ((DateTime?) property.GetValue(en, null)).Value.ToItaFormat(), ";"));
                                        else
                                            sb.Append(";");
                                    }
                                    else if (property != null && property.PropertyType == typeof (DateTime))
                                    {
                                        sb.Append(
                                            String.Concat(
                                                ((DateTime) property.GetValue(entity, null)).ToItaFormat(), ";"));
                                    }
                                    else if (property != null)
                                        sb.Append(String.Concat(property.GetValue(en, null), ";"));
                                }
                                else
                                    sb.Append(";");

                                #endregion
                            }
                            else
                            {
                                int index1 = index;
                                property = propertyInfos.FirstOrDefault(pi => pi.Name.Equals(propertiesToExport[index1]));

                                if (property != null && property.PropertyType == typeof (DateTime?))
                                {
                                    if (property.GetValue(entity, null) != null)
                                        sb.Append(
                                            String.Concat(
                                                ((DateTime?) property.GetValue(entity, null)).Value.ToItaFormat(), ";"));
                                    else
                                        sb.Append(";");
                                }
                                else if (property != null && property.PropertyType == typeof (DateTime))
                                {
                                    sb.Append(
                                        String.Concat(
                                            ((DateTime) property.GetValue(entity, null)).ToItaFormat(), ";"));
                                }
                                else if (property != null)
                                    sb.Append(String.Concat(property.GetValue(entity, null), ";"));
                            }
                        }

                        sb.Append(Environment.NewLine);
                    }

                    #endregion

                    return sb;
                }
                return null;
            }
            catch
            {
                return null;
            }

        }

If you have any questions, please contact me as well.
See you again soon!

mercoledì 4 giugno 2014

Zipping files/folders and then delete the source.

C# .NET Framework 4.51

In my console application, I want to zip a single file or folder and then delete the source.
For this purpose, I use the ZipFile object for zipping folders and ZipArchive object for zipping files.
The problem is that after zip, I have an exception when I delete the source, because folders or files are in use, so I have resolved with asynchronous programming using a Task object (and arguments) with Async and Await.

private async void ExecuteCommand()
        {
…
// Arguments for async task.
var arguments = new List<string> {zipOutput, sourceName, internalOperation};

var returnedTask = DoTaskAsync(arguments);
bool taskResult = await returnedTask;

if (taskResult)
{
    if (internalOperation.Equals("folder"))
    {
        // Remove the read-only attribute.
        var di = new DirectoryInfo(destinationRepositoryName);

        foreach (var file in di.GetFiles("*", SearchOption.AllDirectories))
            file.Attributes &= ~FileAttributes.ReadOnly;

            Directory.Delete(sourceName, true);
     }
     else
         File.Delete(sourceName);

     Console.WriteLine(Environment.NewLine);
     Console.WriteLine("End zipping file -> " + zipOutput);
 }
…
}

// Signature specifies Task<TResult>
private async Task<bool> DoTaskAsync(IReadOnlyList<string> arguments)
{
    try
    {
         Console.WriteLine(Environment.NewLine);
         if (arguments != null)
         {
             Console.WriteLine("Create zipping file -> " + arguments[0]);
                   
             if (arguments[2].Equals("folder"))
                 ZipFile.CreateFromDirectory(arguments[1], arguments[0], CompressionLevel.Fastest, true);
             else
             {
                 using (var archive = ZipFile.Open(arguments[0], ZipArchiveMode.Create))
                 {
                     var fileInfo = new FileInfo(arguments[1]);
                     archive.CreateEntryFromFile(arguments[1], fileInfo.Name);
                 }
              }
              return true;
         }
         Console.WriteLine("Can't create zip file because arguments are null.");
               
         return false;
     }
     catch (Exception ex)
     {
         return false;
     }
 }

See you soon!

venerdì 4 aprile 2014

Developer Conference 2014

It's a great conference dedicated to .NET developers, for developing client and web applications, Windows Phone and Windows 8.x apps.

http://www.developerconference.it/events/2014/default.aspx

mercoledì 19 marzo 2014

LINQ to entities - Error occured update the entries

C# .NET Framework 4.0, Linq to entities

I have an application that uses Linq to entities for accessing to a SQL Server 2008 database, naturally this application works fine. Therefore, I deploy it in a system where there is SQL 2005 express and not SQL Server 2008 and my application gives the follow exception:

Message: An error occurred while updating the entries. See the inner exception for details.

The solution is:

  • Open the entity data model, for example Model.edmx, with a XML Editor.
  • Change the attribute ProviderManifestToken (Schema element -> <Schema …)
          from
      ProviderManifestToken="2008"
      to
      ProviderManifestToken="2005"
  • Rebuild and re-deploy the assembly.

It works fine for me.

venerdì 7 febbraio 2014

WorkShop Android a Chioggia

Ciao a tutti, un'iniziativa interessante per chi vuol muovere i primi passi con Android.

Se siete interessati ecco il link: http://goo.gl/SDV354

giovedì 30 gennaio 2014

Community Days 2014

Organized by Italian community and user group devoted to Microsoft products and technologies, to offer study days in the form of technical conferences.


 Community Days 2014

martedì 14 gennaio 2014

Calling a WCF service through a proxy server.

C# .NET Framework 4.0

I have an application client that calls a WCF service and in this client uses a proxy for the internet connection, so when I call my service I must first provide the proxy authentication.
I have created a class that implements the IWebProxy interface:

namespace Utililty {
   public class ProxyConfig : IWebProxy {

        public ICredentials Credentials {
            get
            {
                using (var context = new AOEntities())
                {
                    var query =
                        from data in context.ConnectionParameters
                        where data.ServerName.Equals("Proxy")
                        select data;

                    if (query.Any())
                    {
                        var parameters = query.FirstOrDefault();
                        if (parameters != null) return new NetworkCredential(parameters.UserName, parameters.Password);
                    }

                    return null;
                }               
            }
            set { }
        }

        public Uri GetProxy(Uri destination) {
            return WebRequest.GetSystemWebProxy().GetProxy(destination);
        }

        public bool IsBypassed(Uri host) {
            return WebRequest.GetSystemWebProxy().IsBypassed(host);
        }       
    }
}

In this example, I retrieve the credentials from a SQL Server database, but if you prefer you can put in the application configuration file.

Then in the application configuration file (app.config), I have added this section:

 <system.net>
   <defaultProxy>
     <module type=" Utililty.ProxyConfig, Utililty"/>
   </defaultProxy>
 </system.net>

and the attribute useDefaultWebProxy="true" at the WCF binding configuration.

The ProxyConfig object will have call automatically before your call to service.

Peace & Love!