Ejemplo n.º 1
0
        // Procedura molto pesante!!!
        // Trasforma un csv in un dizionario di liste una rappresentazione in memoria di una tabella in forma normale
        public static Dictionary<string, List<string>> GetView(System.IO.Stream stream, Mapping mapping, int maxResult = 0, int offSet = 0)
        {
            if (stream == null) return null;
                if (mapping == null) return null;

                Dictionary<string, List<string>> view = new Dictionary<string, List<string>>();
                stream.Seek(0, System.IO.SeekOrigin.Begin);

                //create object for CSVReader and pass the stream
                CSVReader reader = new CSVReader((System.IO.Stream)stream);

                string[] dataRow;
                int indexRow = 0;

                try
                {
                    while ((dataRow = reader.GetCSVLine()) != null)
                    {
                        // offset salto le  offSet righe del csv
                        if (indexRow >= offSet)
                        {
                            foreach (MappingItem item in mapping.Items)
                            {
                                int numColumn = int.Parse(item._a.ToString());
                                string data = dataRow[numColumn - 1];
                                string header = item._b.ToString();

                                if (header.ToUpper() == "TIME_PERIOD")
                                    if (mapping.TranscodeUse)
                                        data = mapping.TranscodeTime.TransCodific(data);

                                if (view.Keys.Contains<string>(header))
                                {

                                    if (maxResult > 0
                                        && ((List<string>)view[header]).Count >= maxResult)
                                        return view;

                                    ((List<string>)view[header]).Add(data.Trim());
                                }
                                else
                                {
                                    view.Add(header, new List<string>());
                                    ((List<string>)view[header]).Add(data.Trim());
                                }
                            }

                        }

                        indexRow++;

                    }
                    return view;
                }
                catch (Exception ex)
                {
                    //Console.Write(ex.Message);
                }
            return null;
        }
Ejemplo n.º 2
0
        public string UploadFileCSV()
        {
            // Retrive Logged user
            SDMX_Dataloader.Engine.Client client = null;
            try
            {
                client = HttpContext.Current.Session[UserDef.UserSessionKey] as SDMX_Dataloader.Engine.Client; if (client == null) throw new Exception("Session Expiried");
            }
            catch (Exception ex)
            {
                return JsonMessage.SessionExpired;
            }

            try
            {

                if (!UserDef.UserCan(client.LoggedUser, UserDef.ActionDef.DefaultProc))
                    return JsonMessage.GetError(Resources.Notification.err_action_denied);

                #region Check file successfull sended

                if (!HttpContext.Current.Request.Files.AllKeys.Any())
                    return JsonMessage.GetError(Resources.Notification.err_file_not_found);

                var httpPostedFile = HttpContext.Current.Request.Files["UploadedCSV"];
                //create object for CSVReader and pass the stream
                System.IO.Stream _stream = httpPostedFile.InputStream;

                if (_stream == null)
                    return JsonMessage.GetError(Resources.Notification.err_file_csv);

                // Get the uploaded image from the Files collection
                string[] _params_row = HttpContext.Current.Request.Params.GetValues("chkFirstRowJump");
                string[] _params = HttpContext.Current.Request.Params.GetValues("CharSeparator");
                bool firstRowHeader = (_params_row[0].Trim() == "true") ? true : false;
                char csvSeparator = _params[0].Trim()[0];
                // check file type (only .csv)
                string[] FileExt = httpPostedFile.FileName.Split('.');
                string FileEx = FileExt[FileExt.Length - 1];
                if (FileEx.ToLower() != "csv")
                {
                    return JsonMessage.GetError(Resources.Notification.err_file_bad_type);
                }
                // Check file exist
                if (httpPostedFile.ContentLength < 1)
                {
                    return JsonMessage.GetError(Resources.Notification.err_file_empty);
                }
                #endregion

                CSVReader reader = new CSVReader((System.IO.Stream)_stream);
                reader.Separator = csvSeparator;
                string[] headers = (firstRowHeader) ? reader.GetHeaders() : reader.GetCSVLine();
                string _userPath = HttpContext.Current.Server.MapPath(client.UserDirectory + System.IO.Path.DirectorySeparatorChar);
                string filename = System.IO.Path.GetFileName(httpPostedFile.FileName);
                string fileSavePath = System.IO.Path.Combine(_userPath,filename.Substring(0,filename.Length-4));
                int contentLength = httpPostedFile.ContentLength;
                string contentType = httpPostedFile.ContentType;

                string[] row = reader.GetHeaders();

                int indexTimeFormat = -1;
                for (int i = 0; i < headers.Length;i++ )
                {
                    if (headers[i].ToUpper() == "TIME_PERIOD") {
                        indexTimeFormat = i;
                        break;
                    }
                }
                string timeformat = (indexTimeFormat>-1)?row[indexTimeFormat]:"1900-10";

                _stream.Close();
                httpPostedFile.InputStream.Close();

                Dictionary<string, object> _param = new Dictionary<string, object>();
                _param.Add("filename", filename);
                _param.Add("filesize", contentLength);
                _param.Add("content", contentType);
                _param.Add("headers", headers);
                _param.Add("timeformat", timeformat);

                // force json responce header
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/json";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.Write(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(_param));
                HttpContext.Current.Response.End();
                //HttpContext.Current.ApplicationInstance.CompleteRequest();
                return JsonMessage.GetData(_param);

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return JsonMessage.ErrorOccured;
            }
        }