Skip to content

Instantly share code, notes, and snippets.

@feanz
Created November 30, 2017 17:59
Show Gist options
  • Save feanz/0cbb2ffe740777b6a3ce081476307513 to your computer and use it in GitHub Desktop.
Save feanz/0cbb2ffe740777b6a3ce081476307513 to your computer and use it in GitHub Desktop.
[Serializable]
public class ExportSearchToFile : Command
{
private string _linkToFile = string.Empty;
public override void Execute(CommandContext context)
{
if (context.Items.Length == 0)
return;
Item obj = context.Items[0];
NameValueCollection parameters = new NameValueCollection();
parameters["id"] = obj.ID.ToString();
parameters["language"] = obj.Language.ToString();
parameters["version"] = obj.Version.ToString();
parameters["database"] = obj.Database.Name;
string[] values = context.Parameters.GetValues("url");
if (values != null)
parameters["searchString"] = values[0].Replace("\"", string.Empty);
Context.ClientPage.Start((object) this, "Run", parameters);
}
protected void Run(ClientPipelineArgs args)
{
Assert.ArgumentNotNull((object) args, nameof (args));
if (args.IsPostBack)
{
if (!(args.Result == "yes"))
return;
Database database = Factory.GetDatabase(args.Parameters["database"]);
Assert.IsNotNull((object) database, "Database \"" + args.Parameters["database"] + "\" not found.");
Item obj = database.Items[args.Parameters["id"], Language.Parse(args.Parameters["language"]), Sitecore.Data.Version.Parse(args.Parameters["version"])];
List<SearchStringModel> searchQuery = SearchStringModel.ExtractSearchQuery(args.Parameters["searchString"]);
Assert.IsNotNull((object) obj, "item");
ProgressBox.Execute(Translate.Text("Export to File"), Translate.Text("Exporting list to file"), "~/icon/Software/32x32/text_code.png", new ProgressBoxMethod(this.StartProcess), new object[3]
{
(object) obj,
(object) searchQuery,
(object) args.Result
});
if (!string.IsNullOrEmpty(this._linkToFile))
{
SheerResponse.Download(this._linkToFile);
SheerResponse.Alert(string.Format("Finished exporting all search results.", Array.Empty<object>()), Array.Empty<string>());
}
else
SheerResponse.Alert(string.Format("No results found to export.", Array.Empty<object>()), Array.Empty<string>());
}
else
{
SheerResponse.Confirm("Are you sure you want to export all results?");
args.WaitForPostBack();
}
}
private void StartProcess(params object[] parameters)
{
string parameter1 = (string) parameters[2];
Item parameter2 = (Item) parameters[0];
SitecoreIndexableItem sitecoreIndexableItem = SitecoreIndexableItem.op_Implicit(parameter2);
if (sitecoreIndexableItem == null)
{
Log.Error("Export to file - Unable to cast current item - " + parameters[0].GetType().FullName, (object) this);
}
else
{
List<SearchStringModel> parameter3 = (List<SearchStringModel>) parameters[1];
using (IProviderSearchContext searchContext = ContentSearchManager.GetIndex((IIndexable) sitecoreIndexableItem).CreateSearchContext((SearchSecurityOptions) 0))
{
int num = 0;
IQueryable<SitecoreUISearchResultItem> query = (IQueryable<SitecoreUISearchResultItem>) LinqHelper.CreateQuery<SitecoreUISearchResultItem>(searchContext, (IEnumerable<SearchStringModel>) parameter3, parameter2, (IEnumerable<IExecutionContext>) null);
List<Item> source = new List<Item>();
using (IEnumerator<SitecoreUISearchResultItem> enumerator = ((IEnumerable<SitecoreUISearchResultItem>) query).GetEnumerator())
{
while (((IEnumerator) enumerator).MoveNext())
{
Item obj = enumerator.Current.GetItem();
if (obj != null && obj.Security.CanWrite((Account) Context.User) && obj.Name != "__Standard Values")
source.Add(obj);
}
}
if (source.Count > 0)
{
StreamWriter streamWriter = (StreamWriter) null;
try
{
string str1 = "/temp/" + (DateUtil.IsoNow + "_Export") + ".csv";
string str2 = str1.Replace("/", "\\").Substring(1, str1.Length - 1);
Log.Info("Exporting file to: " + System.Web.HttpRuntime.AppDomainAppPath + str2, nameof (StartProcess));
streamWriter = new StreamWriter((Stream) new FileStream(System.Web.HttpRuntime.AppDomainAppPath + str2, FileMode.Create, FileAccess.Write), Encoding.UTF8);
Item obj1 = source.FirstOrDefault<Item>();
List<string> stringList1 = new List<string>();
foreach (Field field in obj1.Fields.ToList<Field>())
{
if (!string.IsNullOrEmpty(field.Name))
stringList1.Add(field.Name);
}
streamWriter.WriteLine("Id," + string.Join(",", (IEnumerable<string>) stringList1));
foreach (Item obj2 in source)
{
++num;
if (obj2 != null)
{
List<string> stringList2 = new List<string>();
stringList2.Add(obj2.ID.ToString());
foreach (string index in stringList1)
{
string str3 = string.Empty;
if (!string.IsNullOrEmpty(obj2.Fields[index].Value))
{
string typeKey = obj2.Fields[index].TypeKey;
str3 = typeKey == "datetime" ? (DateField) obj2.Fields[index].DateTime.ToString((IFormatProvider) CultureInfo.InvariantCulture) : (typeKey == "droplink" ? (LookupField) obj2.Fields[index].TargetItem.DisplayName : obj2.Fields[index].Value);
}
stringList2.Add("\"" + str3.Replace("\"", "\"\"") + "\"");
}
streamWriter.WriteLine(string.Join(",", (IEnumerable<string>) stringList2));
}
}
streamWriter.Flush();
streamWriter.Close();
Log.Audit((object) this, "Export to file details: Exported a total of {0} items", new string[1]
{
num.ToString((IFormatProvider) CultureInfo.InvariantCulture)
});
this._linkToFile = str1;
}
catch (Exception ex)
{
Log.Error("Exception in Export to File - Search: " + ex.Message, (object) this);
this._linkToFile = "An error occurred - please contact Support.";
if (streamWriter != null)
streamWriter.Close();
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment