PageRenderTime 36ms CodeModel.GetById 20ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 0ms

/Src/uSiteBuilder.Admin/ExportCode.ascx.cs

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