public OrderChangelog GenerateInitialChangelog(int datasetId)
        {
            string downloadUriBase = ServerConfigData.DownloadUriBase().TrimEnd('/');

            using (geosyncEntities db = new geosyncEntities())
            {
                var initialChangelog = (from d in db.StoredChangelogs
                                        where d.DatasetId == datasetId && d.StartIndex == 1 && d.Stored == true && d.Status == "finished"
                                        orderby d.DateCreated descending
                                        select d).FirstOrDefault();
                if (initialChangelog != null && initialChangelog.DownloadUri != null)
                {
                    Uri uri = new Uri(initialChangelog.DownloadUri);
                    ChangelogManager.DeleteFileOnServer(uri);
                    db.StoredChangelogs.DeleteObject(initialChangelog);
                    db.SaveChanges();
                }
            }
            LastChangeId = 1;    // StartIndex always 1 on initial changelog
            int endIndex = Convert.ToInt32(GetLastIndex(datasetId));
            int count    = 1000; // TODO: Get from dataset table

            Logger.Info("GenerateInitialChangelog START");
            StoredChangelog ldbo = new StoredChangelog();

            ldbo.Stored     = true;
            ldbo.Status     = "queued";
            ldbo.StartIndex = (int)LastChangeId;

            ldbo.DatasetId   = datasetId;
            ldbo.DateCreated = DateTime.Now;

            //TODO make filter
            //TODO check if similar stored changelog is already done
            using (geosyncEntities db = new geosyncEntities())
            {
                // Store changelog info in database
                db.StoredChangelogs.AddObject(ldbo);

                OrderChangelog resp = new OrderChangelog();
                resp.changelogId = ldbo.ChangelogId.ToString();

                //New thread and do the work....
                // We're coming back to the thread handling later...
                //string sourceFileName = "Changelogfiles/41_changelog.xml";


                Directory.CreateDirectory(destPath);
                // Loop and create xml files
                while (OptimizedChangelLogIndex < OptimizedChangeLog.Count)
                {
                    string partFileName = DateTime.Now.Ticks + ".xml";

                    string fullPathWithFile = Path.Combine(destPath, partFileName);
                    MakeChangeLog((int)LastChangeId, count, PDbConnectInfo, _pWfsUrl, fullPathWithFile, datasetId);
                    LastChangeId += 1;
                }

                // Save endIndex to database
                ldbo.EndIndex = endIndex;

                // New code to handle FTP download
                ChangeLogHandler chgLogHandler = new ChangeLogHandler(ldbo, Logger);
                string           inFile        = "";
                try
                {
                    inFile = destPath;
                    chgLogHandler.CreateZipFileFromFolder(inFile, zipFile, destFileName);
                    ldbo.Status = "queued";
                    File.Copy(tmpzipFile, streamFileLocation);
                    File.Delete(tmpzipFile);
                    ldbo.Status = "finished";
                }
                catch (Exception ex)
                {
                    Logger.ErrorException(string.Format("Failed to create or upload file {0}", zipFile), ex);
                    throw ex;
                }

                try
                {
                    string downLoadUri = string.Format(@"{0}/{1}", downloadUriBase, zipFile);

                    ldbo.DownloadUri = downLoadUri;
                }
                catch (Exception ex)
                {
                    Logger.ErrorException(string.Format("Failed to create or upload file {0}", zipFile), ex);
                    throw ex;
                }


                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Logger.ErrorException(
                        string.Format(
                            "Failed on SaveChanges, Kartverket.Geosynkronisering.ChangelogProviders.PostGISChangelog.OrderChangelog startIndex:{0} count:{1} changelogId:{2}",
                            LastChangeId, count, ldbo.ChangelogId), ex);
                    throw ex;
                }
                Logger.Info(
                    "Kartverket.Geosynkronisering.ChangelogProviders.PostGISChangelog.OrderChangelog" +
                    " startIndex:{0}" + " count:{1}" + " changelogId:{2}", LastChangeId, count, ldbo.ChangelogId);

                Logger.Info("GenerateInitialChangelog END");
                return(resp);
            }
        }
        private OrderChangelog _OrderChangelog(int startIndex, int count, string todoFilter, int datasetId)
        {
            string downloadUriBase = ServerConfigData.DownloadUriBase().TrimEnd('/');

            using (geosyncEntities db = new geosyncEntities())
            {
                ChangelogManager chlmng = new ChangelogManager(db);

                chlmng.SetStatus(_currentOrderChangeLog.changelogId, ChangelogStatusType.working);
                //System.IO.File.Copy(Utils.BaseVirtualAppPath + sourceFileName, Utils.BaseVirtualAppPath + destFileName);
                try
                {
                    if (!Directory.Exists(destPath))
                    {
                        Directory.CreateDirectory(destPath);
                    }
                    MakeChangeLog(startIndex, count, PDbConnectInfo, _pWfsUrl, destPath + destFileName + ".xml",
                                  datasetId);
                }
                catch (Exception ex)
                {
                    chlmng.SetStatus(_currentOrderChangeLog.changelogId, ChangelogStatusType.cancelled);
                    Logger.ErrorException(
                        string.Format("Failed to make Change Log {0}", destPath + destFileName + ".xml"), ex);
                    throw ex;
                }

                // New code to handle FTP download
                ChangeLogHandler chgLogHandler = new ChangeLogHandler(Logger);
                string           inFile        = "";
                try
                {
                    inFile = destPath;
                    chgLogHandler.CreateZipFileFromFolder(inFile, zipFile, destFileName);
                    File.Copy(tmpzipFile, streamFileLocation);
                    File.Delete(tmpzipFile);
                }
                catch (Exception ex)
                {
                    chlmng.SetStatus(_currentOrderChangeLog.changelogId, ChangelogStatusType.cancelled);
                    Logger.ErrorException(string.Format("Failed to create or upload file {0}", zipFile), ex);
                    throw ex;
                }

                try
                {
                    string downLoadUri = string.Format(@"{0}/{1}", downloadUriBase, zipFile);
                    chlmng.SetStatus(_currentOrderChangeLog.changelogId, ChangelogStatusType.finished);
                    chlmng.SetDownloadURI(_currentOrderChangeLog.changelogId, downLoadUri);
                }
                catch (Exception ex)
                {
                    Logger.ErrorException(string.Format("Failed to create or upload file {0}", zipFile), ex);
                    throw ex;
                }

                Logger.Info(
                    "Kartverket.Geosynkronisering.ChangelogProviders.PostGISChangelog.OrderChangelog" +
                    " startIndex:{0}" + " count:{1}" + " changelogId:{2}", startIndex, count,
                    _currentOrderChangeLog.changelogId);

                Logger.Info("OrderChangelog END");
                return(_currentOrderChangeLog);
            }
        }