Skip to content

Instantly share code, notes, and snippets.

@sreekrishnan1993
Last active November 6, 2023 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sreekrishnan1993/e64376973041b4c431c5af096d980d84 to your computer and use it in GitHub Desktop.
Save sreekrishnan1993/e64376973041b4c431c5af096d980d84 to your computer and use it in GitHub Desktop.
Sitecore Forms Custom Email Export
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Ajax.Utilities;
using Microsoft.Extensions.DependencyInjection;
using MyProject.Models;
using Sitecore;
using Sitecore.Common;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.DataProviders;
using Sitecore.Data.Items;
using Sitecore.DependencyInjection;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Client.Pipelines.GetFormFields;
using Sitecore.ExperienceForms.Configuration;
using Sitecore.ExperienceForms.Data;
using Sitecore.ExperienceForms.Data.Entities;
using Sitecore.ExperienceForms.Data.SqlServer.Constants;
using Sitecore.ExperienceForms.Data.SqlServer.Constants.StoredProcedureParameters;
using Sitecore.Mvc.Pipelines;
using Context = Sitecore.Context;
namespace MyProject.Providers
{
public class CsvExportProvider : ICsvExportDataProvider
{
private readonly CultureInfo _culture;
private readonly string _dateFormat;
private readonly string _delimiter;
public bool IsLocalTime;
public double TimeZoneOffset;
private readonly IFormDataProvider _formDataProvider;
public CsvExportProvider(IFormDataProvider formDataProvider)
: this(formDataProvider, ServiceLocator.ServiceProvider.GetService<IFormsConfigurationSettings>())
{
}
public CsvExportProvider(IFormDataProvider formDataProvider, IFormsConfigurationSettings formsConfigurationSettings)
{
Assert.ArgumentNotNull(formDataProvider, "formDataProvider");
Assert.ArgumentNotNull(formsConfigurationSettings, "formsConfigurationSettings");
_formDataProvider = formDataProvider;
if (formsConfigurationSettings is FormsConfigurationSettings formsConfigurationSettings2)
{
_culture = formsConfigurationSettings2.ExportCulture;
_dateFormat = formsConfigurationSettings2.ExportDateFormat ?? "yyyy-MM-dd HH:mm";
_delimiter = formsConfigurationSettings2.ExportDelimiter;
}
}
public ExportDataResult Export(Guid formId, DateTime? startDate, DateTime? endDate, bool isEmailExportForm)
{
string content = string.Empty;
var hostName = Context.HttpContext.Request.Url.Host;
var scheme = Context.HttpContext.Request.Url.Scheme;
IEnumerable<FormEntry> enumerable = null;
if (isEmailExportForm)
{
var result = Task.Run(() => ExportData(formId, startDate, endDate, hostName, scheme, isEmailExportForm));
}
else
{
enumerable = _formDataProvider.GetEntries(formId, (!IsLocalTime) ? startDate : startDate?.AddHours(TimeZoneOffset), (!IsLocalTime) ? endDate : endDate?.AddHours(TimeZoneOffset)).AsEnumerable();
content = ((enumerable == null) ? string.Empty : GenerateFileContent(formId, enumerable));
}
return new ExportDataResult
{
Content = ((enumerable == null) ? string.Empty : GenerateFileContent(formId, enumerable)),
FileName = GenerateFileName(formId, startDate, endDate)
};
}
private void ExportData(Guid formId, DateTime? startDate, DateTime? endDate, string hostName, string scheme, bool isEmailExportForm)
{
string emailBody = string.Empty;
string emailSubject = string.Empty;
var database = Factory.GetDatabase("master");
Item formItem = database.GetItem(new ID(formId));
try
{
Sitecore.Diagnostics.Log.Info("BulkFormImport : Starting Export Data", this);
var createcsv = CreateCSV(formId, startDate, endDate, isEmailExportForm);
if (createcsv.isExportSuccess)
{
string urlPart = string.Empty;
var tempfolder = Sitecore.IO.FileUtil.MapPath(Settings.TempFolderPath);
Uri exportPathURI = new Uri(createcsv.FinalExportPath);
if (exportPathURI.LocalPath.Contains(tempfolder) && !string.IsNullOrEmpty(hostName))
urlPart = exportPathURI.LocalPath.Replace(tempfolder, string.Empty);
var finalOutputPath = $"{scheme}://{hostName}/temp/{urlPart}";
emailBody = "Your Sitecore form export is complete for <b>" + formItem.Name + "</b>. Please <a href=\"" + finalOutputPath + "\"> click here</a> to download the file.";
emailSubject = "Sitecore: Your form export is complete";
}
else
{
if (createcsv.FileContent.Equals(string.Empty))
{
emailSubject = "Sitecore: No Data in your form export";
emailBody = "No Data available for your Sitecore form export. Please try with different options or contact your administrator";
}
else
{
emailSubject = "Sitecore: Your form export is failed";
emailBody = "Your Sitecore form export is failed for some reason. Please try to export after sometime. Contact your administrator if you still face the issue.";
}
}
Sitecore.Diagnostics.Log.Info("BulkFormImport : Finished Export Data", this);
}
catch (Exception ex)
{
emailSubject = "Sitecore: Exception Occured in your form Export";
emailBody = "Your Sitecore form export is failed for some reason. Please try to export after sometime. Contact your administrator if you still face the issue.";
Sitecore.Diagnostics.Log.Error("BulkFormImport: Error During ExportData" + ex.Message, ex, this);
}
emailBody = emailBody + "<br><br>" + "Please do not reply to this email, as it is automatically generated. If you need Sitecore assistance, please contact sitecoresupport@testing.com.";
SendEmail(emailBody, emailSubject);
}
private CustomExportResult CreateCSV(Guid formId, DateTime? startDate, DateTime? endDate, bool isEmailExportForm)
{
CustomExportResult customExportResult = new CustomExportResult();
try
{
Sitecore.Diagnostics.Log.Info("BulkFormImport : Create CSV Started : ", this);
var database = Factory.GetDatabase("master");
Item formItem = database.GetItem(new ID(formId));
var formEntries = GetCustomEntries(formId, startDate, endDate, formItem);
string formContent = string.Empty;
if (isEmailExportForm)
{
formContent = formEntries == null ? string.Empty : GenerateFileContentCustom(formItem, formEntries);
}
else
{
formContent = formEntries == null ? string.Empty : GenerateFileContent(formId, formEntries);
}
string fileName = GenerateFileName(formId, startDate, endDate);
var exportFolderPath = "FormData\\Export\\";
var tempfolder = Sitecore.IO.FileUtil.MapPath(Settings.TempFolderPath);
var finalExportFolderPath = Path.Combine(tempfolder, exportFolderPath);
if (!Directory.Exists(finalExportFolderPath))
{
Directory.CreateDirectory(finalExportFolderPath);
}
var finalPath = Path.Combine(finalExportFolderPath, fileName);
if (File.Exists(finalPath))
{
File.Delete(finalPath);
}
customExportResult.FileContent = formContent;
if (formContent == string.Empty)
{
customExportResult.isExportSuccess = false;
customExportResult.FinalExportPath = string.Empty;
return customExportResult;
}
Sitecore.Diagnostics.Log.Info("BulkFormImport : Final Path : " + finalPath, this);
TextWriter sw = new StreamWriter(finalPath, true, Encoding.UTF8);
sw.Write(formContent.ToString());
sw.Close();
Sitecore.Diagnostics.Log.Info("BulkFormImport : Create CSV Ended - Created and Saved File : " + finalPath, this);
customExportResult.isExportSuccess = true;
customExportResult.FinalExportPath = finalPath;
return customExportResult;
}
catch (Exception ex)
{
var message = ex != null ? ex.ToString() : "Exception is empty";
Sitecore.Diagnostics.Log.Error("BulkFormImport : Error While Creating/Saving File - Exception Message : " + message, ex, this);
customExportResult.isExportSuccess = false;
customExportResult.FinalExportPath = string.Empty; ;
return customExportResult;
}
}
protected virtual string GenerateFileContentCustom(Item formItem, IEnumerable<FormEntry> formEntries)
{
Assert.ArgumentNotNull((object)formEntries, nameof(formEntries));
List<FieldData> fieldColumnsList = new List<FieldData>();
var orderFields = formItem?.Axes?.GetDescendants()?.ToList();
if (orderFields == null)
return string.Empty;
foreach (var fieldItem in orderFields)
{
var fieldData = formEntries.SelectMany(f => f.Fields).FirstOrDefault(fd => fd.FieldItemId == fieldItem.ID.Guid);
if (fieldData != null)
fieldColumnsList.Add(new FieldData { FieldItemId = fieldData.FieldItemId, FieldName = fieldItem.Name });
}
fieldColumnsList = fieldColumnsList.OrderBy(fc => orderFields.IndexOf(orderFields.FirstOrDefault(o => o.ID.Guid == fc.FieldItemId))).ToList();
if (fieldColumnsList.Count == 0)
return string.Empty;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "Created{0}", _delimiter);
stringBuilder.AppendLine(string.Join(_delimiter, fieldColumnsList.Select((FieldData f) => f.FieldName).ToArray()));
int count = fieldColumnsList.Count;
foreach (FormEntry formEntry in formEntries.OrderByDescending(fe => fe.Created))
{
stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH:mm}{1}", IsLocalTime ? formEntry.Created.AddHours(0.0 - TimeZoneOffset) : formEntry.Created, _delimiter);
string[] strArray = new string[count];
for (int index = 0; index < count; ++index)
{
FieldData fieldItem = fieldColumnsList[index];
FieldData fieldData = formEntry.Fields.FirstOrDefault<FieldData>((Func<FieldData, bool>)(f => f.FieldItemId == fieldItem.FieldItemId));
strArray[index] = EscapeCsvDelimiters(FormatFieldValue(fieldData));
}
stringBuilder.AppendLine(string.Join(_delimiter, strArray));
}
return stringBuilder.ToString();
}
public IReadOnlyCollection<FormEntry> GetCustomEntries(Guid formId, DateTime? startDate, DateTime? endDate, Item formItem)
{
string StoredProcedureName = "[" + DatabaseSchema.Storage + "].[" + StoredProcedures.FormDataRetrieve + "]";
Sitecore.Diagnostics.Log.Info("BulkFormImport : formId : " + formId.ToString() + " startDate" + (startDate.HasValue ? startDate.Value.ToString() : string.Empty) + " endDate" + (endDate.HasValue ? endDate.Value.ToString() : string.Empty), this);
IReadOnlyList<FormEntry> result = null;
var connectionString = Settings.GetConnectionString("experienceforms");
IRetryable retryer = Factory.GetRetryer();
try
{
SqlConnection connection = new SqlConnection(connectionString);
try
{
SqlCommand command = connection.CreateCommand();
try
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = StoredProcedureName;
SetParameters(command.Parameters, formId, startDate, endDate);
return retryer.Execute(delegate
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
result = Parse(reader);
}
connection.Close();
return result;
});
}
finally
{
if (command != null)
{
((IDisposable)command).Dispose();
}
}
}
finally
{
if (connection != null)
{
((IDisposable)connection).Dispose();
}
}
}
catch (Exception exception)
{
Sitecore.Diagnostics.Log.Error("Forms database communication error.", exception, this);
}
return result;
}
private void SetParameters(SqlParameterCollection parameters, Guid FormDefinitionId, DateTime? StartDate, DateTime? EndDate)
{
parameters.Add(new SqlParameter(FormDataRetrieve.FormDefinitionId, FormDefinitionId));
if (StartDate.HasValue)
{
parameters.Add(new SqlParameter(FormDataRetrieve.StartDate, StartDate));
}
if (EndDate.HasValue)
{
parameters.Add(new SqlParameter(FormDataRetrieve.EndDate, EndDate));
}
}
public IReadOnlyList<FormEntry> Parse(DbDataReader dataReader)
{
Assert.ArgumentNotNull(dataReader, "dataReader");
Dictionary<Guid, FormEntry> dictionary = new Dictionary<Guid, FormEntry>();
while (dataReader.Read())
{
FormEntry formEntry = ParseFormEntry(dataReader);
dictionary.Add(formEntry.FormEntryId, formEntry);
}
dataReader.NextResult();
while (dataReader.Read())
{
FieldData fieldData = ParseFieldData(dataReader);
if (dictionary.ContainsKey(fieldData.FormEntryId))
{
FormEntry formEntry2 = dictionary[fieldData.FormEntryId];
formEntry2.Fields.Add(fieldData);
}
}
return dictionary.Select((KeyValuePair<Guid, FormEntry> x) => x.Value).ToList();
}
protected virtual FormEntry ParseFormEntry(DbDataReader dataReader)
{
Guid formEntryId = (Guid)dataReader[FormDataRetrieve.FormEntryId];
Guid formItemId = (Guid)dataReader[FormDataRetrieve.FormEntryFormDefinitionId];
DateTime created = (DateTime)dataReader[FormDataRetrieve.FormEntryCreated];
return new FormEntry
{
FormEntryId = formEntryId,
FormItemId = formItemId,
Created = created,
Fields = new List<FieldData>()
};
}
protected virtual FieldData ParseFieldData(DbDataReader dataReader)
{
Guid fieldDataId = (Guid)dataReader[FormDataRetrieve.FieldDataId];
Guid formEntryId = (Guid)dataReader[FormDataRetrieve.FieldDataFormEntryId];
Guid fieldItemId = (Guid)dataReader[FormDataRetrieve.FieldDataFieldDefinitionId];
string fieldName = (string)dataReader[FormDataRetrieve.FieldDataFieldName];
string value = (string)dataReader[FormDataRetrieve.FieldDataValue];
string valueType = (string)dataReader[FormDataRetrieve.FieldDataValueType];
return new FieldData
{
FieldDataId = fieldDataId,
FormEntryId = formEntryId,
FieldItemId = fieldItemId,
FieldName = fieldName,
Value = value,
ValueType = valueType
};
}
private bool SendEmail(string emailMessage, string emailSubject)
{
var currentUser = Context.User.Profile;
var emailAddress = currentUser.Email;
MailMessage mailMessage;
try
{
mailMessage = new MailMessage
{
From = new MailAddress("FormsExport@testing.com"),
Subject = emailSubject,
Body = emailMessage,
IsBodyHtml = true
};
}
catch (Exception exception)
{
Sitecore.Diagnostics.Log.Error("Send Email Action Error", exception, this);
return false;
}
if (!AddEmailAddresses(emailAddress, "To", mailMessage))
{
Sitecore.Diagnostics.Log.Error("Send Email Action Error: No TO address(es) specified.", this);
return false;
}
try
{
SmtpClient smtpClient = GetSmtpClient();
smtpClient.Send(mailMessage);
return true;
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error("Send Email Action Error: " + ex.Message, ex, this);
return false;
}
}
private bool AddEmailAddresses(string addressValue, string fieldName, MailMessage mailMessage)
{
if (string.IsNullOrWhiteSpace(addressValue) || string.IsNullOrWhiteSpace(fieldName) || mailMessage == null)
{
return false;
}
string[] array = addressValue.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
MailAddressCollection mailAddressCollection = mailMessage.GetType().GetProperty(fieldName).GetValue(mailMessage) as MailAddressCollection;
if (array.Length == 0 || mailAddressCollection == null)
{
return false;
}
string[] array2 = array;
foreach (string text in array2)
{
try
{
MailAddress item = new MailAddress(text);
mailAddressCollection.Add(item);
}
catch
{
Sitecore.Diagnostics.Log.Warn("Send Email Action Warning: {text} in the " + fieldName.ToUpperInvariant() + " field is not a valid email address.", this);
}
}
return mailAddressCollection.Count > 0;
}
private SmtpClient GetSmtpClient()
{
SmtpClient smtpClient = new SmtpClient();
string mailServer = Settings.GetSetting("MailServer");
//string mailServer = "smtp.gmail.com";
string mailServerUserName = Settings.GetSetting("MailServerUserName");
//string mailServerUserName = "testertesting009@gmail.com";
string mailServerPassword = Settings.GetSetting("MailServerPassword");
//string mailServerPassword = "#testertesting";
int mailServerPort = Settings.GetIntSetting("MailServerPort", 0);
//int mailServerPort = 587;
if (!string.IsNullOrWhiteSpace(mailServer))
{
smtpClient.Host = mailServer;
}
if (!string.IsNullOrWhiteSpace(mailServerUserName))
{
smtpClient.Credentials = new NetworkCredential(mailServerUserName, (!string.IsNullOrWhiteSpace(mailServerPassword)) ? mailServerPassword : string.Empty);
}
if (mailServerPort > 0)
{
smtpClient.Port = mailServerPort;
}
smtpClient.EnableSsl = true;
return smtpClient;
}
protected virtual string GenerateFileName(Guid formId, DateTime? startDate, DateTime? endDate)
{
string text = string.Empty;
if (startDate.HasValue)
{
text = text + "_from_" + DateUtil.ToIsoDate(startDate.Value);
}
if (endDate.HasValue)
{
text = text + "_until_" + DateUtil.ToIsoDate(endDate.Value);
}
if (string.IsNullOrEmpty(text))
{
text = "-" + DateUtil.IsoNow;
}
return FormattableString.Invariant($"Form-Data{text}.csv");
}
[Obsolete("Try to use 'GenerateFileContent(Guid, IEnumerable<FormEntry>)' method.")]
protected virtual string GenerateFileContent(IEnumerable<FormEntry> formEntries)
{
Assert.ArgumentNotNull(formEntries, "formEntries");
FormEntry formEntry = formEntries.FirstOrDefault();
if (formEntry != null)
{
return GenerateFileContent(formEntry.FormItemId, formEntries);
}
return string.Empty;
}
protected virtual string GenerateFileContent(Guid formId, IEnumerable<FormEntry> formEntries)
{
Assert.ArgumentNotNullOrEmpty(new ID(formId), "formId");
Assert.ArgumentNotNull(formEntries, "formEntries");
FormEntry[] array = formEntries.OrderByDescending((FormEntry item) => item.Created).ToArray();
List<FieldData> list = new List<FieldData>();
StringBuilder stringBuilder = new StringBuilder();
if (array.Length != 0)
{
list = GetFormInputFields(formId, array).ToList();
}
if (list.Count == 0)
{
return string.Empty;
}
stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "Created{0}", _delimiter);
stringBuilder.AppendLine(string.Join(_delimiter, list.Select((FieldData f) => f.FieldName).ToArray()));
int count = list.Count;
FormEntry[] array2 = array;
foreach (FormEntry formEntry in array2)
{
stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0:yyyy-MM-dd HH:mm}{1}", IsLocalTime ? formEntry.Created.AddHours(0.0 - TimeZoneOffset) : formEntry.Created, _delimiter);
string[] array3 = new string[count];
for (int j = 0; j < count; j++)
{
FieldData fieldItem = list[j];
FieldData fieldData = formEntry.Fields.FirstOrDefault((FieldData f) => f.FieldItemId == fieldItem.FieldItemId);
array3[j] = EscapeCsvDelimiters(FormatFieldValue(fieldData));
}
stringBuilder.AppendLine(string.Join(_delimiter, array3));
}
return stringBuilder.ToString();
}
private string EscapeCsvDelimiters(string fieldValue)
{
if (!string.IsNullOrEmpty(fieldValue))
{
fieldValue = fieldValue.Replace("\"", "\"\"");
if (fieldValue.IndexOf(Environment.NewLine, 0, StringComparison.OrdinalIgnoreCase) >= 0 || fieldValue.IndexOf(_delimiter, StringComparison.OrdinalIgnoreCase) >= 0 || fieldValue.IndexOf("\"", StringComparison.OrdinalIgnoreCase) >= 0)
{
fieldValue = FormattableString.Invariant($"\"{fieldValue}\"");
}
}
return fieldValue;
}
protected virtual string FormatFieldValue(FieldData fieldData)
{
if (fieldData == null)
{
return null;
}
string text = fieldData.Value;
DateTime result;
if (fieldData.ValueType == typeof(List<StoredFileInfo>).ToString())
{
text = ConvertFileIdsToDownloadLink(text);
}
else if (fieldData.ValueType == typeof(DateTime).ToString() && DateTime.TryParseExact(text, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
text = result.ToString(_dateFormat, _culture);
}
return text;
}
private static string ConvertFileIdsToDownloadLink(string fileIdString)
{
string[] source = fileIdString.Split(',');
return source.Select(FormatToDownloadLink).Aggregate((string x, string y) => x + "," + y);
}
private static string FormatToDownloadLink(string fileId)
{
if (!Guid.TryParse(fileId, out var _))
{
return fileId;
}
return Globals.ServerUrl + "/sitecore/api/ssc/forms/formdata/formdata/DownloadFile?fileId=" + fileId;
}
private static IEnumerable<FieldData> GetFormInputFields(Guid formId, IEnumerable<FormEntry> formData)
{
Database database = Sitecore.Data.Database.GetDatabase("master");
using GetFormFieldsEventArgs args = new GetFormFieldsEventArgs(database, formId, inputFieldsOnly: true);
GetFormFieldsEventArgs getFormFieldsEventArgs = PipelineService.Get().RunPipeline("forms.getFormFields", args, (GetFormFieldsEventArgs a) => a);
if (getFormFieldsEventArgs.Aborted || !string.IsNullOrEmpty(getFormFieldsEventArgs.Message))
{
return Enumerable.Empty<FieldData>();
}
FieldData[] allFieldsUnordered = formData.SelectMany((FormEntry entry) => entry.Fields).DistinctBy((FieldData field) => field.FieldItemId).ToArray();
FieldData[] array = getFormFieldsEventArgs.Fields.Select((Item fi) => allFieldsUnordered.FirstOrDefault((FieldData field) => field.FieldItemId == fi.ID.Guid) ?? new FieldData
{
FieldName = fi.Name
}).ToArray();
IEnumerable<FieldData> second = allFieldsUnordered.Except(array).Select(delegate (FieldData f)
{
f.FieldName += " [Deprecated]";
return f;
});
return array.Union(second);
}
}
}
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using MyProject.Models;
using MyProject.Providers;
using Sitecore.ExperienceContentManagement.Administration.Helpers.SupportPackage.Diagnostics.Base;
using Sitecore.ExperienceForms.Client.Filters;
using Sitecore.ExperienceForms.Client.Models.Builder;
using Sitecore.ExperienceForms.Data;
using Sitecore.Globalization;
using Sitecore.Services.Core;
using Sitecore.Services.Infrastructure.Web.Http;
using Sitecore.Services.Infrastructure.Web.Http.Filters;
namespace MyProject.Controllers
{
[ServicesController("Forms.ExportData.Custom")]
[SitecoreAuthorize(Roles = "sitecore\\Forms Data Administrator")]
[SetFormMode]
public class ExportCustomDataController : ServicesApiController
{
private readonly ICsvExportDataProvider _exportDataProvider;
private readonly HttpContext _httpContext;
public ExportCustomDataController(ICsvExportDataProvider exportDataProvider)
: this(exportDataProvider, HttpContext.Current)
{
}
public ExportCustomDataController(ICsvExportDataProvider exportDataProvider, HttpContext httpContext)
{
Assert.ArgumentNotNull(exportDataProvider, "exportDataProvider");
_exportDataProvider = exportDataProvider;
_httpContext = httpContext;
}
[HttpGet]
[ActionName("DefaultAction")]
[ValidateModelState]
public HttpResponseMessage ExportToCsv([FromUri] CustomExportDataparameters exportDataParameters)
{
HttpResponseMessage val = new HttpResponseMessage();
try
{
if (exportDataParameters == null)
{
val.StatusCode = HttpStatusCode.BadRequest;
val.ReasonPhrase = Translate.Text("Invalid or missing parameters.");
}
else
{
ExportDataResult exportResult = _exportDataProvider.Export(exportDataParameters.FormId, exportDataParameters.StartDate, exportDataParameters.EndDate, exportDataParameters.isEmailExportForm);
string value = GenerateCookieValue(exportDataParameters, exportResult, val);
_httpContext?.Response.AppendCookie(new HttpCookie("fileDownloadToken" + exportDataParameters.Token, value));
}
HttpResponseMessage result = val;
val = null;
return result;
}
finally
{
if (val != null)
{
val.Dispose();
}
}
}
private string GenerateCookieValue(CustomExportDataparameters exportDataParameters, ExportDataResult exportResult, HttpResponseMessage responseMessage)
{
if (exportDataParameters.isEmailExportForm)
{
return exportDataParameters.Token;
}
if (exportResult == null || string.IsNullOrEmpty(exportResult.Content))
{
return SetNoData(responseMessage, exportDataParameters.IsDateRange);
}
return PopulateCsvData(responseMessage, exportDataParameters, exportResult);
}
private static string SetNoData(HttpResponseMessage response, bool isDateRange)
{
response.StatusCode = (HttpStatusCode.NoContent);
if (isDateRange)
{
response.ReasonPhrase = (Translate.Text("There is no data available for the selected date range."));
return "nodatainrange";
}
return "nodata";
}
private string PopulateCsvData(HttpResponseMessage response, ExportDataParameters exportDataParameters, ExportDataResult exportResult)
{
string text = "\ufeff";
response.Content = ((HttpContent)new StringContent(text + exportResult.Content));
response.Content.Headers.ContentType = (new MediaTypeHeaderValue("application/octet-stream"));
HttpContentHeaders headers = response.Content.Headers;
ContentDispositionHeaderValue val = new ContentDispositionHeaderValue("attachment");
val.FileName = (exportResult.FileName);
headers.ContentDisposition = (val);
return exportDataParameters.Token;
}
}
}
using System;
using Sitecore.ExperienceForms.Data;
namespace MyProject.Providers
{
public interface ICsvExportDataProvider
{
ExportDataResult Export(Guid formId, DateTime? startDate, DateTime? endDate, bool isEmailExportForm);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment