kelvindigital.usitebuilder.package /Src/uSiteBuilder.Admin/ExportCode.ascx.cs

Language C# Lines 381
MD5 Hash 9f94fb000e76899a7f09b673bf996eea Estimated Cost $8,194 (why?)
Repository https://bitbucket.org/gfyans/kelvindigital.usitebuilder.package View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using Vega.USiteBuilder;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.template;
using umbraco.cms.businesslogic.web;

namespace kelvinDigital.USiteBuilderAdmin
{

    public partial class usercontrols_ExportCode : System.Web.UI.UserControl
    {
        private const string code = @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Vega.USiteBuilder;

{7}
{{
    [DocumentType(Name=""{0}"", IconUrl=""{1}"", 
        Alias=""{8}"",
        AllowedTemplates= new string[] {{{2}}},
        AllowedChildNodeTypes = new Type[] {{{3}}})]
    public partial class {4} : {5}
    {{
        public {4} () {{}}
        public {4} (int nodeId) : base(nodeId){{}}
        {6}
    }}
}}";

        private string property = @"
        [DocumentTypeProperty(UmbracoPropertyType.{5}, {6} Name = ""{0}"", Description = ""{1}"", Tab = ""{2}"", Mandatory = {3} )]
        public {7} {4} {{ get; set; }}";

        private const string dataTypeCode = @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.cms.businesslogic.datatype;
using Vega.USiteBuilder;

{6}
{{
    [DataType(Name = ""{0}"", UniqueId = ""{1}"", RenderControlGuid = ""{2}"", DatabaseDataType = {3})]
    public partial class {4} : DataTypeBase
    {{
        public override DataTypePrevalue[] Prevalues
        {{
            get
            {{
                return new DataTypePrevalue[]
                {{
                    {5}
                }};
            }}
        }}
    }}
}}";

        private const string templateCode = @"using System.Web.UI;
using Vega.USiteBuilder;

{0}
{{
    public partial class {1} : TemplateBase{2}
    {{
    }}
}}";

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            txtDataTypesNamespace.Enabled = cbxExportDataTypes.Checked;
            txtDocTypesNamespace.Enabled = cbxExportDocTypes.Checked;
            txtTemplatesNamespace.Enabled = cbxExportTemplates.Checked;
        }

        protected void preview_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            if (cbxExportTemplates.Checked)
            {
                Template.GetAllAsList().ForEach(template => sb.AppendLine(ExportTemplate(template)));
            }
            if (cbxExportDataTypes.Checked)
            {
                DataTypeDefinition.GetAll().ToList().ForEach(dataType => sb.AppendLine(ExportDataType(dataType)));
            }
            if (cbxExportDocTypes.Checked)
            {
                DocumentType.GetAllAsList().ForEach(docType => sb.AppendLine(ExportDocType(docType.Id)));
            }

            litCode.Text = Server.HtmlEncode(sb.ToString());
            activateTab.Visible = true;
        }

        protected void save_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("content-disposition", "attachment; filename=\"Exported uSiteBuilder Classes.zip\"");
            Response.CacheControl = "Private";
            Response.Cache.SetExpires(DateTime.Now.AddMinutes(3));

            var zipStream = new ZipOutputStream(Response.OutputStream);
            zipStream.SetLevel(3);
            if (cbxExportDocTypes.Checked)
            {
                DocumentType.GetAllAsList().ForEach(docType =>
                {
                    string docTypeCode = ExportDocType(docType.Id);
                    var memoryStream = new MemoryStream();

                    using (TextWriter tw = new StreamWriter(memoryStream))
                    {
                        tw.Write(docTypeCode);
                        tw.Flush();

                        ZipEntry newEntry =
                            new ZipEntry("DocumentTypes/" + CleanName(docType.Alias) +
                                         ".cs");
                        newEntry.DateTime = DateTime.Now;
                        zipStream.PutNextEntry(newEntry);
                        memoryStream.Position = 0;

                        StreamUtils.Copy(memoryStream, zipStream, new byte[4096]);

                        zipStream.CloseEntry();
                    }
                });
            }

            if (cbxExportDataTypes.Checked)
            {
                DataTypeDefinition.GetAll().ToList().ForEach(dataType =>
                {
                    string dataTypeCode = ExportDataType(dataType);
                    var memoryStream = new MemoryStream();

                    using (
                        TextWriter tw = new StreamWriter(memoryStream))
                    {
                        tw.Write(dataTypeCode);
                        tw.Flush();

                        ZipEntry newEntry =
                            new ZipEntry("DataTypes/" +
                                         CleanName(dataType.Text) +
                                         ".cs");
                        newEntry.DateTime = DateTime.Now;
                        zipStream.PutNextEntry(newEntry);
                        memoryStream.Position = 0;

                        StreamUtils.Copy(memoryStream, zipStream,
                                         new byte[4096]);

                        zipStream.CloseEntry();
                    }
                });
            }

            if (cbxExportTemplates.Checked)
            {
                Template.GetAllAsList().ForEach(template =>
                {
                    string exportedTemplate = ExportTemplate(template);
                    var memoryStream = new MemoryStream();

                    using (TextWriter tw = new StreamWriter(memoryStream))
                    {
                        tw.Write(exportedTemplate);
                        tw.Flush();

                        ZipEntry newEntry =
                            new ZipEntry("Templates/" + CleanName(template.Alias) +
                                         ".master.cs");
                        newEntry.DateTime = DateTime.Now;
                        zipStream.PutNextEntry(newEntry);
                        memoryStream.Position = 0;

                        StreamUtils.Copy(memoryStream, zipStream, new byte[4096]);

                        zipStream.CloseEntry();
                    }

                    var memoryStream2 = new MemoryStream();

                    using (TextWriter tw = new StreamWriter(memoryStream2))
                    {
                        tw.Write("<%@ Master Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"" + CleanName(template.Alias) + ".master.cs\" Inherits=\"" + txtTemplatesNamespace.Text +"." + CleanName(template.Alias) + "\" %>");

                        string design = template.Design;
                        int startPos = design.IndexOf(">");
                        tw.Write(design.Substring(startPos + 1));
                        tw.Flush();

                        ZipEntry newEntry =
                            new ZipEntry("Templates/" + CleanName(template.Alias) +
                                         ".master");
                        newEntry.DateTime = DateTime.Now;
                        zipStream.PutNextEntry(newEntry);
                        memoryStream2.Position = 0;

                        StreamUtils.Copy(memoryStream2, zipStream, new byte[4096]);

                        zipStream.CloseEntry();
                    }
                });
            }

            zipStream.IsStreamOwner = false;
            zipStream.Close();
            Response.End();
        }


        // these are private readonlys as const can't be Guids
        private readonly Guid DATATYPE_YESNO_GUID = new Guid("38b352c1-e9f8-4fd8-9324-9a2eab06d97a");
        private readonly Guid DATATYPE_TINYMCE_GUID = new Guid("5e9b75ae-face-41c8-b47e-5f4b0fd82f83");
        private readonly Guid DATATYPE_DATETIMEPICKER_GUID = new Guid("b6fb1622-afa5-4bbf-a3cc-d9672a442222");
        private readonly Guid DATATYPE_DATEPICKER_GUID = new Guid("23e93522-3200-44e2-9f29-e61a6fcbb79a");

        private string GetPropertyType (Guid datatype)
        {
            if(datatype == DATATYPE_YESNO_GUID)
            {
                return "bool";
            }
            if(datatype == DATATYPE_TINYMCE_GUID)
            {
                return "HtmlString";
            }
            if(datatype == DATATYPE_DATETIMEPICKER_GUID)
            {
                return "DateTime";
            }
            if(datatype == DATATYPE_DATEPICKER_GUID)
            {
                return "DateTime";
            }

            return "string";
        }

        private string CleanName(string name)
        {
            //Compliant with item 2.4.2 of the C# specification
            System.Text.RegularExpressions.Regex regex =
                new System.Text.RegularExpressions.Regex(
                    @"[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Nl}\p{Mn}\p{Mc}\p{Cf}\p{Pc}\p{Lm}]");
            string ret = regex.Replace(name, ""); //The identifier must start with a character 
		
			ret = ret.Substring(0, 1).ToUpper() + ret.Substring(1, ret.Length - 1);
		
			if (!char.IsLetter(ret, 0))
            {
                ret = string.Concat("_", ret);
            }

            return ret;
        }


        private string ExportTemplate(Template template)
        {
            string docTypeClass = "";

            List<DocumentType> documentTypes = DocumentType.GetAllAsList();
            if (documentTypes.Count(docType => docType.allowedTemplates.Any(tmpl => tmpl.Alias == template.Alias)) == 1)
            {
                var defaultDocumentType =
                    documentTypes.Single(docType => docType.allowedTemplates.Any(tmpl => tmpl.Alias == template.Alias));
                docTypeClass = string.IsNullOrEmpty(txtDocTypesNamespace.Text)
                                   ? string.Format("<{0}>", CleanName(defaultDocumentType.Alias))
                                   : string.Format("<{0}.{1}>", txtDocTypesNamespace.Text,  CleanName(defaultDocumentType.Alias));
            }

            return string.Format(templateCode,
                                 !string.IsNullOrEmpty(txtTemplatesNamespace.Text)
                                     ? "namespace " + txtTemplatesNamespace.Text
                                     : "",
                                 CleanName(template.Alias.Replace(" ", "")),
                                 docTypeClass);
        }

        private string ExportDataType(DataTypeDefinition dataType)
        {
            if (dataType.DataType == null)
            {
                return "";
            }

            var defaultData = dataType.DataType.Data as DefaultData;

            string dbType = "DBTypes.Nvarchar";

            if (defaultData != null)
            {
                dbType = "DBTypes." + defaultData.DatabaseType;
            }

            string preValues = "";
            var settingsStorage = new DataEditorSettingsStorage();
            var existingSettings = settingsStorage.GetSettings(dataType.Id);

            if (existingSettings.Any())
            {
                preValues = string.Join("," + Environment.NewLine,
                                        existingSettings.Select(
                                            setting =>
                                            string.Format("new DataTypePrevalue(\"{0}\", \"{1}\")", setting.Key,
                                                          setting.Value.Replace("\"", "\\\""))));
            }

            return string.Format(dataTypeCode, dataType.Text.Replace("\"", "\\\""), dataType.UniqueId.ToString(),
                                 dataType.DataType.Id.ToString(), dbType, CleanName(dataType.Text), preValues,
                                 !string.IsNullOrEmpty(txtDataTypesNamespace.Text)
                                     ? "namespace " + txtDataTypesNamespace.Text
                                     : "");
        }

        private string ExportDocType(int id)
        {
            DocumentType docType = new DocumentType(id);

            string templates = String.Join(", ",
                                           docType.allowedTemplates.Select(template => "\"" + template.Alias + "\""));
            string childNodes = String.Join(", ",
                                            docType.AllowedChildContentTypeIDs.Select(
                                                contentTypeId => "typeof(" + CleanName(new DocumentType(contentTypeId).Alias) + ")"));

            string properties = String.Join(string.Empty,
                                            docType.getVirtualTabs.SelectMany(
                                                tab =>
                                                tab.GetPropertyTypes(id, false).Select(
                                                    prop =>
                                                    String.Format(property, prop.Name.Replace("\"", "\\\""), prop.Description.Replace(Environment.NewLine, "").Replace("\"", "\\\""),
                                                                  (prop.TabId == 0
                                                                       ? "Properties"
                                                                       : umbraco.cms.businesslogic.ContentType.Tab.
                                                                             GetTab(prop.TabId).Caption),
                                                                  prop.Mandatory.ToString().ToLower(), CleanName(prop.Alias),
                                                                  Enum.IsDefined(typeof(UmbracoPropertyType),
                                                                                 prop.DataTypeDefinition.Id)
                                                                      ? ((UmbracoPropertyType)
                                                                         prop.DataTypeDefinition.Id).ToString()
                                                                      : "Other",
                                                                  Enum.IsDefined(typeof(UmbracoPropertyType),
                                                                                 prop.DataTypeDefinition.Id)
                                                                      ? ""
                                                                      : "OtherTypeName=\"" +
                                                                        prop.DataTypeDefinition.Text.Replace("\"", "\\\"") + "\", ",
                                                                        GetPropertyType(umbraco.cms.businesslogic.ContentType.GetDataType(docType.Alias, prop.Alias))))));
            return string.Format(code,
                                 docType.Text.Replace("\"", "\\\""),
                                 docType.IconUrl,
                                 templates,
                                 childNodes,
                                 CleanName(docType.Alias),
                                 (docType.MasterContentType == 0
                                      ? "DocumentTypeBase"
                                      : CleanName(new DocumentType(docType.MasterContentType).Alias)),
                                 properties,
                                 !string.IsNullOrEmpty(txtDocTypesNamespace.Text)
                                     ? "namespace " + txtDocTypesNamespace.Text
                                     : "",
                                docType.Alias.Replace("\"", "\\\""));
        }
    }
}
Back to Top