PageRenderTime 21ms CodeModel.GetById 2ms app.highlight 14ms RepoModel.GetById 2ms app.codeStats 0ms

/umbraco/plugins/uSiteBuilderAdmin/ExportCode.ascx.cs

https://bitbucket.org/Mulliman/usitebuilder-back-office-extension-forked-from-kelvindigital
C# | 378 lines | 322 code | 54 blank | 2 comment | 26 complexity | ef00875ca602ebd4e607f5ddfdced685 MD5 | raw file
  1namespace USiteBuilderBackOffice.Umbraco4.Plugins.uSiteBuilderAdmin
  2{
  3    using System;
  4    using System.Collections.Generic;
  5    using System.IO;
  6    using System.Linq;
  7    using System.Text;
  8    using System.Web;
  9    using System.Web.UI.WebControls;
 10    using ICSharpCode.SharpZipLib.Core;
 11    using ICSharpCode.SharpZipLib.Zip;
 12    using Vega.USiteBuilder;
 13    using umbraco.cms.businesslogic.datatype;
 14    using umbraco.cms.businesslogic.template;
 15    using umbraco.cms.businesslogic.web;
 16
 17    public partial class ExportCode : System.Web.UI.UserControl
 18    {
 19        private const string code = @"
 20using System;
 21using System.Collections.Generic;
 22using System.Linq;
 23using System.Web;
 24using Vega.USiteBuilder;
 25{7}
 26{{
 27    [DocumentType(Name=""{0}"", IconUrl=""{1}"", 
 28        Alias=""{8}"",
 29        AllowedTemplates= new string[] {{{2}}},
 30        AllowedChildNodeTypes = new Type[] {{{3}}})]
 31    public partial class {4} : {5}
 32    {{
 33        public {4} (int nodeId) : base(nodeId){{}}
 34        public {4} () {{}}
 35        {6}
 36    }}
 37}}";
 38
 39        private string property = @"
 40        [DocumentTypeProperty(UmbracoPropertyType.{5}, {6} Name = ""{0}"", Description = ""{1}"", Tab = ""{2}"", Mandatory = {3} )]    
 41        public {7} {4} {{ get; set; }}
 42";
 43
 44        private const string dataTypeCode = @"
 45    using System;
 46    using System.Collections.Generic;
 47    using System.Linq;
 48    using System.Web;
 49    using umbraco.cms.businesslogic.datatype;
 50    using Vega.USiteBuilder;
 51    {6}
 52    {{
 53        [DataType(Name = ""{0}"", UniqueId = ""{1}"", RenderControlGuid = ""{2}"", DatabaseDataType = {3})]
 54        public partial class {4} : DataTypeBase
 55        {{
 56            public override DataTypePrevalue[] Prevalues
 57            {{
 58                get {{ return new DataTypePrevalue[] {{ {5} }}; }}
 59            }}
 60        }}
 61    }}";
 62
 63        private const string templateCode = @"
 64
 65    using System.Web.UI;
 66    using Vega.USiteBuilder;
 67
 68    {0}
 69    {{
 70        public partial class {1} : TemplateBase{2}
 71        {{
 72        }}
 73    }}
 74";
 75
 76        protected override void OnLoad(EventArgs e)
 77        {
 78            base.OnLoad(e);
 79
 80            DataTypesNamespaceTextBox.Enabled = ExportDataTypesCheckBox.Checked;
 81            DocTypesNamespaceTextBox.Enabled = ExportDocTypesCheckBox.Checked;
 82            TemplatesNamespaceTextBox.Enabled = ExportTemplatesCheckBox.Checked;
 83        }
 84
 85        protected void Preview_Click(object sender, EventArgs e)
 86        {
 87            StringBuilder sb = new StringBuilder();
 88
 89            if (ExportTemplatesCheckBox.Checked)
 90            {
 91                Template.GetAllAsList().ForEach(template => sb.AppendLine(ExportTemplate(template)));
 92            }
 93            if (ExportDataTypesCheckBox.Checked)
 94            {
 95                DataTypeDefinition.GetAll().ToList().ForEach(dataType => sb.AppendLine(ExportDataType(dataType)));
 96            }
 97            if (ExportDocTypesCheckBox.Checked)
 98            {
 99                DocumentType.GetAllAsList().ForEach(docType => sb.AppendLine(ExportDocType(docType.Id)));
100            }
101
102            CodeLiteral.Text = Server.HtmlEncode(sb.ToString());
103            ActivateTabPlaceHolder.Visible = true;
104        }
105
106        protected void Save_Click(object sender, EventArgs e)
107        {
108            Response.ContentType = "application/octet-stream";
109            Response.AppendHeader("content-disposition", "attachment; filename=\"Exported uSiteBuilder Classes.zip\"");
110            Response.CacheControl = "Private";
111            Response.Cache.SetExpires(DateTime.Now.AddMinutes(3));
112
113            var zipStream = new ZipOutputStream(Response.OutputStream);
114            zipStream.SetLevel(3);
115            if (ExportDocTypesCheckBox.Checked)
116            {
117                DocumentType.GetAllAsList().ForEach(docType =>
118                {
119                    string docTypeCode = ExportDocType(docType.Id);
120                    var memoryStream = new MemoryStream();
121
122                    using (TextWriter tw = new StreamWriter(memoryStream))
123                    {
124                        tw.Write(docTypeCode);
125                        tw.Flush();
126
127                        ZipEntry newEntry =
128                            new ZipEntry("DocumentTypes/" + CleanName(docType.Alias) +
129                                         ".cs");
130                        newEntry.DateTime = DateTime.Now;
131                        zipStream.PutNextEntry(newEntry);
132                        memoryStream.Position = 0;
133
134                        StreamUtils.Copy(memoryStream, zipStream, new byte[4096]);
135
136                        zipStream.CloseEntry();
137                    }
138                });
139            }
140
141            if (ExportDataTypesCheckBox.Checked)
142            {
143                DataTypeDefinition.GetAll().ToList().ForEach(dataType =>
144                {
145                    string dataTypeCode = ExportDataType(dataType);
146                    var memoryStream = new MemoryStream();
147
148                    using (
149                        TextWriter tw = new StreamWriter(memoryStream))
150                    {
151                        tw.Write(dataTypeCode);
152                        tw.Flush();
153
154                        ZipEntry newEntry =
155                            new ZipEntry("DataTypes/" +
156                                         CleanName(dataType.Text) +
157                                         ".cs");
158                        newEntry.DateTime = DateTime.Now;
159                        zipStream.PutNextEntry(newEntry);
160                        memoryStream.Position = 0;
161
162                        StreamUtils.Copy(memoryStream, zipStream,
163                                         new byte[4096]);
164
165                        zipStream.CloseEntry();
166                    }
167                });
168            }
169
170            if (ExportTemplatesCheckBox.Checked)
171            {
172                Template.GetAllAsList().ForEach(template =>
173                {
174                    string exportedTemplate = ExportTemplate(template);
175                    var memoryStream = new MemoryStream();
176
177                    using (TextWriter tw = new StreamWriter(memoryStream))
178                    {
179                        tw.Write(exportedTemplate);
180                        tw.Flush();
181
182                        ZipEntry newEntry =
183                            new ZipEntry("Templates/" + CleanName(template.Alias) +
184                                         ".master.cs");
185                        newEntry.DateTime = DateTime.Now;
186                        zipStream.PutNextEntry(newEntry);
187                        memoryStream.Position = 0;
188
189                        StreamUtils.Copy(memoryStream, zipStream, new byte[4096]);
190
191                        zipStream.CloseEntry();
192                    }
193
194                    var memoryStream2 = new MemoryStream();
195
196                    using (TextWriter tw = new StreamWriter(memoryStream2))
197                    {
198                        tw.Write("<%@ Master Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"" + CleanName(template.Alias) + ".master.cs\" Inherits=\"" + TemplatesNamespaceTextBox.Text + "." + CleanName(template.Alias) + "\" %>");
199
200                        string design = template.Design;
201                        int startPos = design.IndexOf(">");
202                        tw.Write(design.Substring(startPos + 1));
203                        tw.Flush();
204
205                        ZipEntry newEntry =
206                            new ZipEntry("Templates/" + CleanName(template.Alias) +
207                                         ".master");
208                        newEntry.DateTime = DateTime.Now;
209                        zipStream.PutNextEntry(newEntry);
210                        memoryStream2.Position = 0;
211
212                        StreamUtils.Copy(memoryStream2, zipStream, new byte[4096]);
213
214                        zipStream.CloseEntry();
215                    }
216                });
217            }
218
219            zipStream.IsStreamOwner = false;
220            zipStream.Close();
221            Response.End();
222        }
223
224
225        // these are private readonlys as const can't be Guids
226        private readonly Guid DATATYPE_YESNO_GUID = new Guid("38b352c1-e9f8-4fd8-9324-9a2eab06d97a");
227        private readonly Guid DATATYPE_TINYMCE_GUID = new Guid("5e9b75ae-face-41c8-b47e-5f4b0fd82f83");
228        private readonly Guid DATATYPE_DATETIMEPICKER_GUID = new Guid("b6fb1622-afa5-4bbf-a3cc-d9672a442222");
229        private readonly Guid DATATYPE_DATEPICKER_GUID = new Guid("23e93522-3200-44e2-9f29-e61a6fcbb79a");
230
231        private string GetPropertyType(Guid datatype)
232        {
233            if (datatype == DATATYPE_YESNO_GUID)
234            {
235                return "bool";
236            }
237            if (datatype == DATATYPE_TINYMCE_GUID)
238            {
239                return "HtmlString";
240            }
241            if (datatype == DATATYPE_DATETIMEPICKER_GUID)
242            {
243                return "DateTime";
244            }
245            if (datatype == DATATYPE_DATEPICKER_GUID)
246            {
247                return "DateTime";
248            }
249
250            return "string";
251        }
252
253        private string CleanName(string name)
254        {
255            //Compliant with item 2.4.2 of the C# specification
256            System.Text.RegularExpressions.Regex regex =
257                new System.Text.RegularExpressions.Regex(
258                    @"[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Nl}\p{Mn}\p{Mc}\p{Cf}\p{Pc}\p{Lm}]");
259            string ret = regex.Replace(name, ""); //The identifier must start with a character 
260
261            ret = ret.Substring(0, 1).ToUpper() + ret.Substring(1, ret.Length - 1);
262
263            if (!char.IsLetter(ret, 0))
264            {
265                ret = string.Concat("_", ret);
266            }
267
268            return ret;
269        }
270
271
272        private string ExportTemplate(Template template)
273        {
274            string docTypeClass = "";
275
276            List<DocumentType> documentTypes = DocumentType.GetAllAsList();
277            if (documentTypes.Count(docType => docType.allowedTemplates.Any(tmpl => tmpl.Alias == template.Alias)) == 1)
278            {
279                var defaultDocumentType =
280                    documentTypes.Single(docType => docType.allowedTemplates.Any(tmpl => tmpl.Alias == template.Alias));
281                docTypeClass = string.IsNullOrEmpty(DocTypesNamespaceTextBox.Text)
282                                   ? string.Format("<{0}>", CleanName(defaultDocumentType.Alias))
283                                   : string.Format("<{0}.{1}>", DocTypesNamespaceTextBox.Text, CleanName(defaultDocumentType.Alias));
284            }
285
286            return string.Format(templateCode,
287                                 !string.IsNullOrEmpty(TemplatesNamespaceTextBox.Text)
288                                     ? "namespace " + TemplatesNamespaceTextBox.Text
289                                     : "",
290                                 CleanName(template.Alias.Replace(" ", "")),
291                                 docTypeClass);
292        }
293
294        private string ExportDataType(DataTypeDefinition dataType)
295        {
296            if (dataType.DataType == null)
297            {
298                return "";
299            }
300
301            var defaultData = dataType.DataType.Data as DefaultData;
302
303            string dbType = "DBTypes.Nvarchar";
304
305            if (defaultData != null)
306            {
307                dbType = "DBTypes." + defaultData.DatabaseType;
308            }
309
310            string preValues = "";
311            var settingsStorage = new DataEditorSettingsStorage();
312            var existingSettings = settingsStorage.GetSettings(dataType.Id);
313
314            if (existingSettings.Any())
315            {
316                preValues = string.Join("," + Environment.NewLine,
317                                        existingSettings.Select(
318                                            setting =>
319                                            string.Format("new DataTypePrevalue(\"{0}\", \"{1}\")", setting.Key,
320                                                          setting.Value.Replace("\"", "\\\""))));
321            }
322
323            return string.Format(dataTypeCode, dataType.Text.Replace("\"", "\\\""), dataType.UniqueId.ToString(),
324                                 dataType.DataType.Id.ToString(), dbType, CleanName(dataType.Text), preValues,
325                                 !string.IsNullOrEmpty(DataTypesNamespaceTextBox.Text)
326                                     ? "namespace " + DataTypesNamespaceTextBox.Text
327                                     : "");
328        }
329
330        private string ExportDocType(int id)
331        {
332            DocumentType docType = new DocumentType(id);
333
334            string templates = String.Join(", ",
335                                           docType.allowedTemplates.Select(template => "\"" + template.Alias + "\""));
336            string childNodes = String.Join(", ",
337                                            docType.AllowedChildContentTypeIDs.Select(
338                                                contentTypeId => "typeof(" + CleanName(new DocumentType(contentTypeId).Alias) + ")"));
339
340            string properties = String.Join(string.Empty,
341                                            docType.getVirtualTabs.SelectMany(
342                                                tab =>
343                                                tab.GetPropertyTypes(id, false).Select(
344                                                    prop =>
345                                                    String.Format(property, prop.Name.Replace("\"", "\\\""), prop.Description.Replace(Environment.NewLine, "").Replace("\"", "\\\""),
346                                                                  (prop.TabId == 0
347                                                                       ? "Properties"
348                                                                       : umbraco.cms.businesslogic.ContentType.Tab.
349                                                                             GetTab(prop.TabId).Caption),
350                                                                  prop.Mandatory.ToString().ToLower(), CleanName(prop.Alias),
351                                                                  Enum.IsDefined(typeof(UmbracoPropertyType),
352                                                                                 prop.DataTypeDefinition.Id)
353                                                                      ? ((UmbracoPropertyType)
354                                                                         prop.DataTypeDefinition.Id).ToString()
355                                                                      : "Other",
356                                                                  Enum.IsDefined(typeof(UmbracoPropertyType),
357                                                                                 prop.DataTypeDefinition.Id)
358                                                                      ? ""
359                                                                      : "OtherTypeName=\"" +
360                                                                        prop.DataTypeDefinition.Text.Replace("\"", "\\\"") + "\", ",
361                                                                        GetPropertyType(umbraco.cms.businesslogic.ContentType.GetDataType(docType.Alias, prop.Alias))))));
362            return string.Format(code,
363                                 docType.Text.Replace("\"", "\\\""),
364                                 docType.IconUrl,
365                                 templates,
366                                 childNodes,
367                                 CleanName(docType.Alias),
368                                 (docType.MasterContentType == 0
369                                      ? "DocumentTypeBase"
370                                      : CleanName(new DocumentType(docType.MasterContentType).Alias)),
371                                 properties,
372                                 !string.IsNullOrEmpty(DocTypesNamespaceTextBox.Text)
373                                     ? "namespace " + DocTypesNamespaceTextBox.Text
374                                     : "",
375                                docType.Alias.Replace("\"", "\\\""));
376        }
377    }
378}