aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.CodeGeneration/Helper.cs
blob: af617fe3e537f535a24655fbfb3df8a96f54b8e3 (plain)
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
using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Tango.CodeGeneration
{
    /// <summary>
    /// Contains several code generation helper methods.
    /// </summary>
    public static class Helper
    {
        static Helper()
        {
            var config = new TemplateServiceConfiguration { Debug = true, ReferenceResolver = new CustomResolver() };
            Engine.Razor = RazorEngineService.Create(config);
        }

        /// <summary>
        /// Gets a code template by the code object type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public static String GetTemplate(Type type)
        {
            return GetTemplate(type.Name);
        }

        /// <summary>
        /// Gets a code template by name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static String GetTemplate(String name)
        {
            var assembly = Assembly.GetAssembly(typeof(Helper));
            var resourceName = typeof(Helper).Namespace + ".Templates." + name + ".cshtml";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// Parses the template using Razor Engine.
        /// </summary>
        /// <param name="template">The template.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public static String ParseTemplate(String template, object model)
        {
            return Engine.Razor.RunCompile(template, Guid.NewGuid().ToString(), model.GetType(), model).Replace("<div>", "").Replace("</div>", "");
        }

        /// <summary>
        /// Parses the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public static String Parse(String text,object model)
        {
            return Engine.Razor.RunCompile(text, Guid.NewGuid().ToString(), model.GetType(), model);
        }

        /// <summary>
        /// Indents the c sharp code.
        /// </summary>
        /// <param name="code">The code.</param>
        /// <returns></returns>
        public static string IndentCSharpCode(string code)
        {
            const string INDENT_STEP = "    ";

            if (string.IsNullOrWhiteSpace(code))
            {
                return code;
            }

            var result = new StringBuilder();
            var indent = string.Empty;
            var lineContent = false;
            var stringDefinition = false;

            for (var i = 0; i < code.Length; i++)
            {
                var ch = code[i];

                if (ch == '"' && !stringDefinition)
                {
                    result.Append(ch);
                    stringDefinition = true;
                    continue;
                }

                if (ch == '"' && stringDefinition)
                {
                    result.Append(ch);
                    stringDefinition = false;
                    continue;
                }

                if (stringDefinition)
                {
                    result.Append(ch);
                    continue;
                }

                if (ch == '{' && !stringDefinition)
                {
                    if (lineContent)
                    {
                        result.AppendLine();
                    }

                    result.Append(indent).Append("{");

                    if (lineContent)
                    {
                        result.AppendLine();
                    }

                    indent += INDENT_STEP;
                    lineContent = false;

                    continue;
                }

                if (ch == '}' && !stringDefinition)
                {
                    if (indent.Length != 0)
                    {
                        indent = indent.Substring(0, indent.Length - INDENT_STEP.Length);
                    }

                    if (lineContent)
                    {
                        result.AppendLine();
                    }

                    result.Append(indent).Append("}");

                    if (lineContent)
                    {
                        result.AppendLine();
                    }


                    lineContent = false;

                    continue;
                }

                if (ch == '\r')
                {
                    continue;
                }

                if ((ch == ' ' || ch == '\t') && !lineContent)
                {
                    continue;
                }

                if (ch == '\n')
                {
                    lineContent = false;
                    result.AppendLine();

                    continue;
                }

                if (!lineContent)
                {
                    result.Append(indent);
                    lineContent = true;
                }

                result.Append(ch);
            }

            return result.ToString();
        }
    }
}
s="w"> GetUserTeamMember().DisplayName + " (via Machine Studio)."); updated = await SetWorkItemAssignment(Project, updated, workItem.ResolvedBy); ResolvedWorkItems.Remove(workItem); return updated; } public void Initialize() { Task.Factory.StartNew(() => { if (!IsInitialized) { try { Project = GetProject("Tango").Result; IsInitialized = true; } catch (Exception ex) { LogManager.Log(ex, "Error initializing the Team Foundation Service client."); } } }); } public WorkItem CreateBug() { WorkItem item = new WorkItem(); IAuthenticationProvider auth = TangoIOC.Default.GetInstance<IAuthenticationProvider>(); IStudioApplicationManager app = TangoIOC.Default.GetInstance<IStudioApplicationManager>(); item.Area = Project.Areas.FirstOrDefault(); item.Iteration = Project.Iterations.FirstOrDefault(); TeamMember currentUser = GetUserTeamMember(); if (currentUser == null) { throw LogManager.Default.Log(new AuthenticationException($"User '{user_email}' is not part of the Tango VSTS team. Please contact your administrator.")); } var settings = SettingsManager.Default.GetOrCreate<MachineStudioSettings>(); item.CreatedBy = currentUser; item.ChangedBy = currentUser; item.AuthorizedAs = currentUser; item.FoundInBuild = app.Version.ToString(); item.Priority = Priority.Priority3; item.Severity = Severity.Medium; item.State = State.New; item.Type = WorkItemType.Bug; item.Environment = settings.DeploymentSlot.ToDescription(); item.MachineType = (MachineType)settings.LastConnectedMachineType; foreach (var window in Application.Current.Windows.OfType<Window>().Where(x => !String.IsNullOrWhiteSpace(x.Title))) { var bitmap = UIHelper.TakeSnapshot(window); if (!_tempFolder.Exists()) { _tempFolder = TemporaryManager.CreateFolder(); } var tempFile = _tempFolder.CreateFile(); bitmap.SaveJpeg(tempFile.Path, 30); String title = window.Title; item.Attachments.Add(new Attachment() { Description = title + " Screen Capture", FilePath = tempFile.Path, Name = $"{title}.jpg", }); } return item; } private string[] GetLogFiles(FileLogger logger) { string[] fileEntries = new string[1]; fileEntries[0] = logger.LogFile; string fileName = Path.GetFileNameWithoutExtension(logger.LogFile); int indexPos = fileName.IndexOf(FileLogger.FILE_SET_EXTENSION); if (indexPos > 0) { string extension = Path.GetExtension(logger.LogFile); fileName = fileName.Substring(0, indexPos); fileEntries = Directory.GetFiles(logger.Folder, $"{fileName}*{extension}").Where(x => Path.GetFileName(x).StartsWith(logger.Tag)).OrderBy(x => x.Length).ThenBy(x => x).ToArray(); } return fileEntries; } public void FinalizeBug(WorkItem item) { IAuthenticationProvider auth = TangoIOC.Default.GetInstance<IAuthenticationProvider>(); IStudioApplicationManager app = TangoIOC.Default.GetInstance<IStudioApplicationManager>(); FileLogger appFileLogger = LogManager.Default.RegisteredLoggers.FirstOrDefault(x => x.GetType() == typeof(FileLogger)) as FileLogger; FileLogger embeddedFileLogger = MachineOperator.EmbeddedLogManager.RegisteredLoggers.FirstOrDefault(x => x.GetType() == typeof(FileLogger)) as FileLogger; if (appFileLogger != null) { string[] logFiles = GetLogFiles(appFileLogger); foreach( string file in logFiles) { var appLogFile = _tempFolder.CreateImaginaryFile(); File.Copy(file, appLogFile.Path); item.Attachments.Add(new Attachment() { Description = "Application Log File", FilePath = appLogFile.Path, Name = Path.GetFileName(file), }); } } if (embeddedFileLogger != null && File.Exists(embeddedFileLogger.LogFile)) { string[] logFiles = GetLogFiles(embeddedFileLogger); foreach (string file in logFiles) { var embeddedLogFile = _tempFolder.CreateImaginaryFile(); File.Copy(file, embeddedLogFile.Path); item.Attachments.Add(new Attachment() { Description = "Embedded Log File", FilePath = embeddedLogFile.Path, Name = Path.GetFileName(file), }); } } //Add session log file.. if (MachineOperator.EnableSessionLogFile) { var file = MachineOperator.SessionLogger.LogFile; if (file != null && File.Exists(file)) { var sessionLogFile = _tempFolder.CreateImaginaryFile(); File.Copy(file, sessionLogFile.Path); item.Attachments.Add(new Attachment() { Description = "Session Log File", FilePath = sessionLogFile.Path, Name = Path.GetFileName(file), }); } } SystemInformationModel sysModel = new SystemInformationModel(); sysModel.ApplicationVersion = app.Version.ToString(); sysModel.EmbeddedVersion = "N/A"; sysModel.HostName = Environment.MachineName; sysModel.UserName = auth.CurrentUser.Contact.FullName; if (app.ConnectedMachine != null) { Machine machine = app.Machine; sysModel.Machine = machine; sysModel.EmbeddedVersion = app.ConnectedMachine.DeviceInformation.Version; sysModel.ConfigurationString = machine.Configuration.Clone().ToJsonString(); if (app.ConnectedMachine.CurrentProcessParameters != null) { sysModel.LoadedProcessParametersString = app.ConnectedMachine.CurrentProcessParameters.ToJsonString(nameof(ProcessParametersTable.ProcessParametersTablesGroup)); } if (app.ConnectedMachine.CurrentHardwareConfiguration != null) { sysModel.LoadedHardwareConfigurationString = app.ConnectedMachine.CurrentHardwareConfiguration.ToJsonString(); } } if (app.Machine != null && app.ConnectedMachine != null && app.ConnectedMachine.DeviceInformation != null) { item.EmbeddedVersion = app.ConnectedMachine.DeviceInformation.Version; item.MachineSerialNumber = app.Machine.SerialNumber; } String html = String.Empty; using (var stream = EmbeddedResourceHelper.GetEmbeddedResourceStream("Tango.MachineStudio.UI.TFS.SystemInformationTemplate.cshtml")) { StreamReader reader = new StreamReader(stream); html = reader.ReadToEnd(); } item.SystemInformation = CodeGeneration.Helper.Parse(html, sysModel); item.StepsToReproduce = String.Format("<div style=\"white-space:pre\">{0}</div>", item.StepsToReproduce); } private TeamMember GetUserTeamMember() { IAuthenticationProvider auth = TangoIOC.Default.GetInstance<IAuthenticationProvider>(); TeamMember currentUser = Project.Members.SingleOrDefault(x => x.UniqueName.ToLower().Contains(auth.CurrentUser.Email.ToLower())); return currentUser; } } }