File: ImportCatalogPart.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (501 lines) | stat: -rw-r--r-- 22,476 bytes parent folder | download | duplicates (7)
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//------------------------------------------------------------------------------
// <copyright file="ImportCatalogPart.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.WebControls.WebParts {

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Security;
    using System.Security.Permissions;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Util;
    using System.Xml;

    /// <devdoc>
    /// </devdoc>
    public sealed class ImportCatalogPart : CatalogPart {

        private WebPart _availableWebPart;
        private string _importedPartDescription;
        private WebPartDescriptionCollection _availableWebPartDescriptions;
        private FileUpload _upload;
        private Button _uploadButton;
        private string _importErrorMessage;

        private const int baseIndex = 0;
        private const int importedPartDescriptionIndex = 1;
        private const int controlStateArrayLength = 2;

        private const string TitlePropertyName = "Title";
        private const string DescriptionPropertyName = "Description";
        private const string IconPropertyName = "CatalogIconImageUrl";
        private const string ImportedWebPartID = "ImportedWebPart";

        private static readonly WebPartDescriptionCollection DesignModeAvailableWebPart =
            new WebPartDescriptionCollection(new WebPartDescription[] {
                new WebPartDescription("webpart1", String.Format(CultureInfo.CurrentCulture,
                    SR.GetString(SR.CatalogPart_SampleWebPartTitle), "1"), null, null)});

        [WebCategory("Appearance")]
        [WebSysDefaultValue(SR.ImportCatalogPart_Browse)]
        [WebSysDescription(SR.ImportCatalogPart_BrowseHelpText)]
        public string BrowseHelpText {
            get {
                object o = ViewState["BrowseHelpText"];
                return (o != null) ? (string)o : SR.GetString(SR.ImportCatalogPart_Browse);
            }
            set {
                ViewState["BrowseHelpText"] = value;
            }
        }

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Themeable(false)]
        public override string DefaultButton {
            get { return base.DefaultButton; }
            set { base.DefaultButton = value; }
        }

        [WebCategory("Appearance")]
        [WebSysDefaultValue(SR.ImportCatalogPart_ImportedPartLabel)]
        [WebSysDescription(SR.ImportCatalogPart_ImportedPartLabelText)]
        public string ImportedPartLabelText {
            get {
                object o = ViewState["ImportedPartLabelText"];
                return (o != null) ? (string)o : SR.GetString(SR.ImportCatalogPart_ImportedPartLabel);
            }
            set {
                ViewState["ImportedPartLabelText"] = value;
            }
        }

        [WebCategory("Appearance")]
        [WebSysDefaultValue(SR.ImportCatalogPart_ImportedPartErrorLabel)]
        [WebSysDescription(SR.ImportCatalogPart_PartImportErrorLabelText)]
        public string PartImportErrorLabelText {
            get {
                object o = ViewState["PartImportErrorLabelText"];
                return (o != null) ? (string)o : SR.GetString(SR.ImportCatalogPart_ImportedPartErrorLabel);
            }
            set {
                ViewState["PartImportErrorLabelText"] = value;
            }
        }

        [
        WebSysDefaultValue(SR.ImportCatalogPart_PartTitle),
        ]
        public override string Title {
            get {
                string s = (string)ViewState["Title"];
                return (s != null) ? s : SR.GetString(SR.ImportCatalogPart_PartTitle);
            }
            set {
                ViewState["Title"] = value;
            }
        }

        [WebCategory("Appearance")]
        [WebSysDefaultValue(SR.ImportCatalogPart_UploadButton)]
        [WebSysDescription(SR.ImportCatalogPart_UploadButtonText)]
        public string UploadButtonText {
            get {
                object o = ViewState["UploadButtonText"];
                return (o != null) ? (string)o : SR.GetString(SR.ImportCatalogPart_UploadButton);
            }
            set {
                ViewState["UploadButtonText"] = value;
            }
        }

        [WebCategory("Appearance")]
        [WebSysDefaultValue(SR.ImportCatalogPart_Upload)]
        [WebSysDescription(SR.ImportCatalogPart_UploadHelpText)]
        public string UploadHelpText {
            get {
                object o = ViewState["UploadHelpText"];
                return (o != null) ? (string)o : SR.GetString(SR.ImportCatalogPart_Upload);
            }
            set {
                ViewState["UploadHelpText"] = value;
            }
        }

        protected internal override void CreateChildControls() {
            Controls.Clear();

            _upload = new FileUpload();
            Controls.Add(_upload);

            _uploadButton = new Button();
            _uploadButton.ID = "Upload";
            _uploadButton.CommandName = "upload";
            _uploadButton.Click += new EventHandler(OnUpload);
            Controls.Add(_uploadButton);

            if (!DesignMode && Page != null) {
                IScriptManager scriptManager = Page.ScriptManager;
                if (scriptManager != null) {
                    scriptManager.RegisterPostBackControl(_uploadButton);
                }
            }
        }

        public override WebPartDescriptionCollection GetAvailableWebPartDescriptions() {
            if (DesignMode) {
                return DesignModeAvailableWebPart;
            }

            CreateAvailableWebPartDescriptions();
            return _availableWebPartDescriptions;
        }

        private void CreateAvailableWebPartDescriptions() {
            if (_availableWebPartDescriptions != null) {
                return;
            }

            if (WebPartManager == null || String.IsNullOrEmpty(_importedPartDescription)) {
                _availableWebPartDescriptions = new WebPartDescriptionCollection();
                return;
            }

            // Run in minimal trust
            PermissionSet pset = new PermissionSet(PermissionState.None);
            // add in whatever perms are appropriate
            pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            pset.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));

            pset.PermitOnly();
            bool permitOnly = true;
            string title = null;
            string description = null;
            string icon = null;
            // Extra try-catch block to prevent elevation of privilege attack via exception filter
            try {
                try {
                    // Get the WebPart description from its saved XML description.
                    using (StringReader sr = new StringReader(_importedPartDescription)) {
                        using (XmlReader reader = XmlUtils.CreateXmlReader(sr)) {
                            if (reader != null) {
                                reader.MoveToContent();
                                // Check if imported part is authorized

                                // Get to the metadata
                                reader.MoveToContent();
                                reader.ReadStartElement(WebPartManager.ExportRootElement);
                                reader.ReadStartElement(WebPartManager.ExportPartElement);
                                reader.ReadStartElement(WebPartManager.ExportMetaDataElement);

                                // Get the type name
                                string partTypeName = null;
                                string userControlTypeName = null;
                                while (reader.Name != WebPartManager.ExportTypeElement) {
                                    reader.Skip();
                                    if (reader.EOF) {
                                        throw new EndOfStreamException();
                                    }
                                }
                                if (reader.Name == WebPartManager.ExportTypeElement) {
                                    partTypeName = reader.GetAttribute(WebPartManager.ExportTypeNameAttribute);
                                    userControlTypeName = reader.GetAttribute(WebPartManager.ExportUserControlSrcAttribute);
                                }

                                // If we are in shared scope, we are importing a shared WebPart
                                bool isShared = (WebPartManager.Personalization.Scope == PersonalizationScope.Shared);

                                if (!String.IsNullOrEmpty(partTypeName)) {
                                    // Need medium trust to call BuildManager.GetType()
                                    PermissionSet mediumPset = new PermissionSet(PermissionState.None);
                                    mediumPset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                                    mediumPset.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));

                                    CodeAccessPermission.RevertPermitOnly();
                                    permitOnly = false;
                                    mediumPset.PermitOnly();
                                    permitOnly = true;

                                    Type partType = WebPartUtil.DeserializeType(partTypeName, true);

                                    CodeAccessPermission.RevertPermitOnly();
                                    permitOnly = false;
                                    pset.PermitOnly();
                                    permitOnly = true;

                                    // First check if the type is authorized
                                    if (!WebPartManager.IsAuthorized(partType, null, null, isShared)) {
                                        _importErrorMessage = SR.GetString(SR.WebPartManager_ForbiddenType);
                                        return;
                                    }
                                    // If the type is not a webpart, create a generic Web Part
                                    if (!partType.IsSubclassOf(typeof(WebPart)) && !partType.IsSubclassOf(typeof(Control))) {
                                        // We only allow for Controls (VSWhidbey 428511)
                                        _importErrorMessage = SR.GetString(SR.WebPartManager_TypeMustDeriveFromControl);
                                        return;
                                    }
                                }
                                else {
                                    // Check if the path is authorized
                                    if (!WebPartManager.IsAuthorized(typeof(UserControl), userControlTypeName, null, isShared)) {
                                        _importErrorMessage = SR.GetString(SR.WebPartManager_ForbiddenType);
                                        return;
                                    }
                                }
                                while (!reader.EOF) {
                                    while (!reader.EOF && !(reader.NodeType == XmlNodeType.Element &&
                                            reader.Name == WebPartManager.ExportPropertyElement)) {
                                        reader.Read();
                                    }
                                    if (reader.EOF) {
                                        break;
                                    }
                                    string name = reader.GetAttribute(WebPartManager.ExportPropertyNameAttribute);
                                    if (name == TitlePropertyName) {
                                        title = reader.ReadElementString();
                                    }
                                    else if (name == DescriptionPropertyName) {
                                        description = reader.ReadElementString();
                                    }
                                    else if (name == IconPropertyName) {
                                        string url = reader.ReadElementString().Trim();
                                        if (!CrossSiteScriptingValidation.IsDangerousUrl(url)) {
                                            icon = url;
                                        }
                                    }
                                    else {
                                        reader.Read();
                                        continue;
                                    }
                                    if (title != null && description != null && icon != null) {
                                        break;
                                    }
                                    reader.Read();
                                }
                            }
                        }
                        if (String.IsNullOrEmpty(title)) {
                            title = SR.GetString(SR.Part_Untitled);
                        }

                        _availableWebPartDescriptions = new WebPartDescriptionCollection(
                                new WebPartDescription[] {new WebPartDescription(ImportedWebPartID, title, description, icon)});
                    }
                }
                catch (XmlException) {
                    _importErrorMessage = SR.GetString(SR.WebPartManager_ImportInvalidFormat);
                    return;
                }
                catch {
                    _importErrorMessage = (!String.IsNullOrEmpty(_importErrorMessage)) ?
                        _importErrorMessage :
                        SR.GetString(SR.WebPart_DefaultImportErrorMessage);
                    return;
                }
                finally {
                    if (permitOnly) {
                        // revert if you're not just exiting the stack frame anyway
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
            }
            catch {
                throw;
            }
        }

        public override WebPart GetWebPart(WebPartDescription description) {
            if (description == null) {
                throw new ArgumentNullException("description");
            }

            WebPartDescriptionCollection webPartDescriptions = GetAvailableWebPartDescriptions();
            if (!webPartDescriptions.Contains(description)) {
                throw new ArgumentException(SR.GetString(SR.CatalogPart_UnknownDescription), "description");
            }

            if (_availableWebPart != null) {
                return _availableWebPart;
            }
            // Import the WebPart from its saved XML description.
            using (XmlReader reader = XmlUtils.CreateXmlReader(new StringReader(_importedPartDescription))) {
                if (reader != null && WebPartManager != null) {
                    _availableWebPart = WebPartManager.ImportWebPart(reader, out _importErrorMessage);
                }
            }

            // If import failed, clear the cached description
            if (_availableWebPart == null) {
                _importedPartDescription = null;
                _availableWebPartDescriptions = null;
            }
            return _availableWebPart;
        }

        /// <devdoc>
        /// <para>Loads the control state for those properties that should persist across postbacks
        ///   even when EnableViewState=false.</para>
        /// </devdoc>
        protected internal override void LoadControlState(object savedState) {
            if (savedState == null) {
                base.LoadControlState(null);
            }
            else {
                object[] myState = (object[])savedState;
                if (myState.Length != controlStateArrayLength) {
                    throw new ArgumentException(SR.GetString(SR.Invalid_ControlState));
                }

                base.LoadControlState(myState[baseIndex]);
                if (myState[importedPartDescriptionIndex] != null) {
                    _importedPartDescription = (string)myState[importedPartDescriptionIndex];
                    // Calling this method to be sure to emit any import error message in time:
                    // Otherwise, the descriptions will only be constructed (and the error messages
                    // generated) when the list of imported parts is rendered, which happens after
                    // the importcatalogpart itself is rendered. The error message being rendered
                    // by the ICP, we have to call this now
                    GetAvailableWebPartDescriptions();
                }
            }
        }

        /// <devdoc>
        /// Registers the ImportCatalogPart for control state.
        /// </devdoc>
        protected internal override void OnInit(EventArgs e) {
            base.OnInit(e);
            Page.RegisterRequiresControlState(this);
        }

        internal void OnUpload(object sender, EventArgs e) {
            string fileName = _upload.FileName;
            Stream contents = _upload.FileContent;
            if (!String.IsNullOrEmpty(fileName) && contents != null) {
                using (StreamReader sr = new StreamReader(contents, true)) {
                    _importedPartDescription = sr.ReadToEnd();

                    // Clear cache
                    _availableWebPart = null;
                    _availableWebPartDescriptions = null;
                    _importErrorMessage = null;

                    if (String.IsNullOrEmpty(_importedPartDescription)) {
                        _importErrorMessage = SR.GetString(SR.ImportCatalogPart_NoFileName);
                    }
                    else {
                        GetAvailableWebPartDescriptions();
                    }
                }
            }
            else {
                _importErrorMessage = SR.GetString(SR.ImportCatalogPart_NoFileName);
            }
        }

        /// <devdoc>
        /// <para>Saves the control state for those properties that should persist across postbacks
        ///   even when EnableViewState=false.</para>
        /// </devdoc>
        protected internal override object SaveControlState() {
            object[] myState = new object[controlStateArrayLength];

            myState[baseIndex] = base.SaveControlState();
            myState[importedPartDescriptionIndex] = _importedPartDescription;

            for (int i=0; i < controlStateArrayLength; i++) {
                if (myState[i] != null) {
                    return myState;
                }
            }

            // More performant to return null than an array of null values
            return null;
        }

        protected internal override void Render(HtmlTextWriter writer) {
            if (Page != null) {
                Page.VerifyRenderingInServerForm(this);
            }

            base.Render(writer);
        }

        protected internal override void RenderContents(HtmlTextWriter writer) {
            // HACK: Need this for child controls to be created at design-time when control is inside template
            EnsureChildControls();

            CatalogZoneBase zone = Zone;
            if (zone != null && !zone.LabelStyle.IsEmpty) {
                zone.LabelStyle.AddAttributesToRender(writer, this);
            }
            writer.AddAttribute(HtmlTextWriterAttribute.For, _upload.ClientID);
            writer.RenderBeginTag(HtmlTextWriterTag.Label);
            writer.Write(BrowseHelpText);
            writer.RenderEndTag();
            writer.WriteBreak();

            if (zone != null && !zone.EditUIStyle.IsEmpty) {
                _upload.ApplyStyle(zone.EditUIStyle);
            }
            _upload.RenderControl(writer);
            writer.WriteBreak();

            if (zone != null && !zone.LabelStyle.IsEmpty) {
                zone.LabelStyle.AddAttributesToRender(writer, this);
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Span);
            writer.Write(UploadHelpText);
            writer.RenderEndTag();
            writer.WriteBreak();

            if (zone != null && !zone.EditUIStyle.IsEmpty) {
                _uploadButton.ApplyStyle(zone.EditUIStyle);
            }
            _uploadButton.Text = UploadButtonText;
            _uploadButton.RenderControl(writer);

            if (_importedPartDescription != null || _importErrorMessage != null || DesignMode) {
                writer.WriteBreak();
                if (_importErrorMessage != null) {
                    if (zone != null && !zone.ErrorStyle.IsEmpty) {
                        zone.ErrorStyle.AddAttributesToRender(writer, this);
                    }
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write(PartImportErrorLabelText);
                    writer.RenderEndTag();

                    writer.RenderBeginTag(HtmlTextWriterTag.Hr);
                    writer.RenderEndTag();

                    if (zone != null && !zone.ErrorStyle.IsEmpty) {
                        zone.ErrorStyle.AddAttributesToRender(writer, this);
                    }
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    // We encode the error message because it is user-provided via the import file.
                    writer.WriteEncodedText(_importErrorMessage);
                    writer.RenderEndTag();
                }
                else {
                    if (zone != null && !zone.LabelStyle.IsEmpty) {
                        zone.LabelStyle.AddAttributesToRender(writer, this);
                    }
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write(ImportedPartLabelText);
                    writer.RenderEndTag();

                    writer.RenderBeginTag(HtmlTextWriterTag.Hr);
                    writer.RenderEndTag();
                }
            }
        }
    }
}