Esempio n. 1
0
        /// <summary>
        ///   Instantiates a new <see cref="EnumType"/> object.
        /// </summary>
        /// <param name="info"><see cref="DataInfo"/> object associated with this type.</param>
        /// <param name="possibleValues">Possible values the data type will have to parse. Can be empty.</param>
        /// <exception cref="ArgumentNullException"><paramref name="possibleValues"/> or <paramref name="info"/> is a null reference.</exception>
        public EnumType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            Type = DataType.Enum;
            DisplayName = "Custom Enumeration";

            List<string> valueList = new List<string>();
            foreach(string value in possibleValues)
            {
                string tempValue = value;
                if (!valueList.Contains(tempValue))
                    valueList.Add(tempValue);
            }

            List<string> nameList = new List<string>(valueList.Count);
            foreach(string value in valueList)
            {
                string name = StringUtility.GetUpperCamelCase(value);
                if (nameList.Contains(name))
                    name = CreateAlternativeName(name, nameList);
                nameList.Add(name);
            }

            TypeLookup = new Dictionary<string, string>();
            for(int i = 0; i < valueList.Count; i++)
                TypeLookup.Add(valueList[i], nameList[i]);
        }
Esempio n. 2
0
 public static List<Dictionary<string, object>> GetEntries(string name)
 {
     System.Console.WriteLine(name + ": Loading");
     char[] spl = new char[] { '\t' };
     string data = GetResource(name);
     List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
     string[] entries = data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
     string[] titles = entries[0].Split(spl);
     DataInfo[] headers = new DataInfo[titles.Length];
     for (int i = 0; i < titles.Length; ++i )
     {
         headers[i] = new DataInfo(titles[i]);
     }
     for (int i = 1; i < entries.Length; ++i)
     {
         Dictionary<string, object> o = new Dictionary<string, object>();
         string[] bit = entries[i].Split(spl);
         for (int j = 0; j < bit.Length; ++j)
         {
             o.Add(headers[j].ColumnName, headers[j].Convert(bit[j]));
         }
         results.Add(o);
     }
     Console.WriteLine(name + ": Complete");
     return results;
 }
        public IPAddressType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            Type = DataType.IPAddress;
            IsNullable = false;
            DisplayName = "IPAddress";

            Usings.Add("System.Net");
        }
Esempio n. 4
0
        /// <summary>
        ///   Instantiates a new <see cref="TimeSpanType"/> object.
        /// </summary>
        /// <param name="info"><see cref="DataInfo"/> object associated with this type.</param>
        /// <param name="possibleValues">Possible values the data type will have to parse. Can be empty.</param>
        /// <exception cref="ArgumentNullException"><paramref name="possibleValues"/> or <paramref name="info"/> is a null reference.</exception>
        public TimeSpanType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            Culture = DefaultCulture;

            Type = DataType.TimeSpan;
            DisplayName = "Duration of Time";
            Usings.Add("System.Globalization");
        }
Esempio n. 5
0
        /// <summary>
        ///   Instantiates a new <see cref="DateTimeType"/> object.
        /// </summary>
        /// <param name="info"><see cref="DataInfo"/> object associated with this type.</param>
        /// <param name="possibleValues">Possible values the data type will have to parse. Can be empty.</param>
        /// <exception cref="ArgumentNullException"><paramref name="possibleValues"/> or <paramref name="info"/> is a null reference.</exception>
        public DateTimeType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            DateTimeSelect = DefaultDateTimeSelect;
            Culture = DefaultCulture;

            Type = DataType.DateTime;
            DisplayName = "Date/Time";
        }
Esempio n. 6
0
        /// <summary>
        ///   Instantiates a new <see cref="BooleanType"/> object.
        /// </summary>
        /// <param name="info"><see cref="DataInfo"/> object associated with this type.</param>
        /// <param name="possibleValues">Possible values the data type will have to parse. Can be empty.</param>
        /// <exception cref="ArgumentNullException"><paramref name="possibleValues"/> or <paramref name="info"/> is a null reference.</exception>
        public BooleanType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            AllowTrueFalseStrings = DefaultAllowTrueFalseStrings;
            AllowYesNoStrings = DefaultAllowYesNoStrings;
            AllowZeroOneStrings = DefaultAllowZeroOneStrings;

            Type = DataType.Boolean;
            DisplayName = "Boolean";
        }
Esempio n. 7
0
        public VersionType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            AllowBuild = DefaultAllowBuild;
            AllowRevision = DefaultAllowRevision;

            Type = DataType.Version;
            IsNullable = false;
            DisplayName = "Version";
        }
Esempio n. 8
0
        /// <summary>
        ///   Instantiates a new <see cref="StringType"/> object.
        /// </summary>
        /// <param name="info"><see cref="DataInfo"/> object associated with this type.</param>
        /// <param name="possibleValues">Possible values the data type will have to parse. Can be empty.</param>
        /// <exception cref="ArgumentNullException"><paramref name="possibleValues"/> or <paramref name="info"/> is a null reference.</exception>
        public StringType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            MinimumLength = DefaultMinimumLength;
            MaximumLength = DefaultMaximumLength;

            Type = DataType.String;
            IsNullable = false;
            IsArray = true;
            DisplayName = "String";
        }
Esempio n. 9
0
        /// <summary>
        ///   Instantiates a new <see cref="BaseType"/> object given the representative possible values.
        /// </summary>
        /// <param name="info"><see cref="DataInfo"/> object associated with this type.</param>
        /// <param name="possibleValues">Possible values the data type will have to parse. Can be empty.</param>
        /// <param name="ignoreCase">True if the case of the values should be ignored, false otherwise. May not have any bearing on certain types.</param>
        /// <exception cref="ArgumentNullException"><paramref name="possibleValues"/> or <paramref name="info"/> is a null reference.</exception>
        public BaseType(DataInfo info, string[] possibleValues)
        {
            if (info == null)
                throw new ArgumentNullException("info");
            if (possibleValues == null)
                throw new ArgumentNullException("possibleValues");

            mInfo = info;
            mPossibleValues = possibleValues;
            Usings = new List<string>();
            IsNullable = true;
            IsArray = false;
        }
Esempio n. 10
0
        public MacAddressType(DataInfo info, string[] possibleValues)
            : base(info, possibleValues)
        {
            AllowColonSeparator = DefaultAllowColonSeparator;
            AllowDashSeparator = DefaultAllowDashSeparator;
            AllowDotSeparator = DefaultAllowDotSeparator;

            Type = DataType.MACAddress;
            IsNullable = false;
            DisplayName = "PhysicalAddress";

            Usings.Add("System.Net.NetworkInformation");
            Usings.Add("System.Text.RegularExpressions");
        }
Esempio n. 11
0
 public static void PreProcess(string inputDir, DataInfo dataInfo, string vocabularyFile, string outputfile)
 {
     List<FileInfo> info = new List<FileInfo>();
     for (int root = dataInfo.startRootID; root <= dataInfo.endRootID; root++)
     {
         for (int leaf = dataInfo.startLeafID; leaf <= dataInfo.endLeafID; leaf++)
         {
             string fileName = string.Format("cate{0}_C{1}QuestionAnswersTerms.dat", root, leaf);
             string fullpath = Path.Combine(inputDir, fileName);
             if (File.Exists(fullpath))
                 info.Add(new FileInfo(fullpath));
         }
     }
     PreProcess(info.ToArray(), vocabularyFile, outputfile);
 }
Esempio n. 12
0
		public Task<SignatureManifest> GetSignatureManifestAsync(DataInfo dataInfo)
		{
			return Task.Factory.StartNew(() =>
			{
				signatureBuidInProgress.GetOrAdd(dataInfo.Name, new ReaderWriterLockSlim())
									   .EnterUpgradeableReadLock();
				IEnumerable<SignatureInfo> signatureInfos = null;

				try
				{
					var lastUpdate = _signatureRepository.GetLastUpdate();

					if (lastUpdate == null || lastUpdate < dataInfo.CreatedAt)
					{
						signatureBuidInProgress.GetOrAdd(dataInfo.Name, new ReaderWriterLockSlim())
											   .EnterWriteLock();
						try
						{
							signatureInfos = PrepareSignatures(dataInfo.Name);
						}
						finally
						{
							signatureBuidInProgress.GetOrAdd(dataInfo.Name, new ReaderWriterLockSlim())
												   .ExitWriteLock();
						}
					}
					else
					{
						signatureInfos = _signatureRepository.GetByFileName();
					}
				}
				finally
				{
					signatureBuidInProgress.GetOrAdd(dataInfo.Name, new ReaderWriterLockSlim())
										   .ExitUpgradeableReadLock();
				}

				var result = new SignatureManifest
				{
					FileLength = dataInfo.Length,
					FileName = dataInfo.Name,
					Signatures = SignatureInfosToSignatures(signatureInfos)
				};
				return result;
			});
		}
Esempio n. 13
0
		/// <summary>
		///     Returns signature manifest and synchronizes remote cache sig repository
		/// </summary>
		/// <param name="dataInfo"></param>
		/// <param name="token"> </param>
		/// <returns></returns>
        public async Task<SignatureManifest> SynchronizeSignaturesAsync(DataInfo dataInfo, CancellationToken token)
        {
			var remoteSignatureManifest = await synchronizationServerClient.GetRdcManifestAsync(dataInfo.Name);
            if (remoteSignatureManifest.Signatures.Any())
            {
                var sigPairs = PrepareSigPairs(remoteSignatureManifest);
              
                var highestSigName = sigPairs.First().Remote;

                using (var highestSigContent = remoteCacheSignatureRepository.CreateContent(highestSigName))
                {
					await synchronizationServerClient.DownloadSignatureAsync(highestSigName, highestSigContent);
                    await SynchronizePairAsync(sigPairs, token);
                }
            }

            return remoteSignatureManifest;
        }
Esempio n. 14
0
        private bool IsObjectLine(DataInfo dataInfo)
        {
            if (this._useFakeObject)
            {
                return this._fakeObjectFound;
            }

            bool ret = false;
            int numObjPixels = 0;

            for (int index = AppConfiguration.SearchBeginDetectorNum; index < AppConfiguration.SearchEndDetectorNum; index++)
            {
                if (dataInfo.LineData[index].Value <= AppConfiguration.ObjectThreshold)
                {
                    if (++numObjPixels > AppConfiguration.SmallObjectSizeInPixels)
                    {
                        ret = true;
                        break;
                    }
                }
            }

            return ret;
        }
Esempio n. 15
0
        public void Print(bool noNewLine, params object[] str)
        {
            //     All positions and sizes are calculated in the unit measurement given by ScaleMode,
            //     when the final numbers are stored in the Data structures then they are converted to
            //     pixels

            SpcInfo sInfo;

            for (int j = 0; j < str.Length; j++)
            {
                string myStr = str[j].ToString();
                if (myStr.Trim(' ').Length == 0)
                {
                    sInfo.Count = (short)myStr.Length;
                    str[j] = sInfo;
                }

                if ((myStr == Environment.NewLine) | (myStr == "\r") | (myStr == "\n") | (myStr == Environment.NewLine))
                {
                    CurrentY += InternalTextHeight;
                    CurrentX = 0;
                }
                else if (myStr == "\t")
                {
                    CurrentX += ConvertFromPixelsX(TabSize);
                }
                else if (str[j] is TabInfo)
                {
                    TabInfo tInfo = ((TabInfo)str[j]);
                    if (tInfo.Column > MaxColumnAvailables)
                        tInfo.Column = (short)(tInfo.Column % MaxColumnAvailables);

                    if (tInfo.Column < 1)
                        tInfo.Column = 1;

                    tInfo.Column--;

                    double tabPos = tInfo.Column * GetColumnSize();
                    if (CurrentX > tabPos)
                        CurrentY += InternalTextHeight;

                    CurrentX = tabPos;
                }
                else if (str[j] is SpcInfo)
                {
                    sInfo = ((SpcInfo)str[j]);
                    if (sInfo.Count > 0)
                    {
                        CurrentX += sInfo.Count * GetColumnSize();
                    }
                }
                else
                {
                    DataInfo newDataInfo = new DataInfo();


                    newDataInfo.Value = myStr;
                    newDataInfo.Color = _currentColor;
                    newDataInfo.Font = (Font)Font.Clone();
                    newDataInfo.X = (float)ConvertToPrinterUnitsX(CurrentX);
                    newDataInfo.Y = (float)ConvertToPrinterUnitsY(CurrentY);

                    _bufferPage.AddDataInfo(newDataInfo);
                    CurrentX += TextWidth(myStr);
                }
            }

            // Adds a Carriage return–linefeed 
            if (!noNewLine)
            {
                CurrentY += InternalTextHeight;
                CurrentX = 0;
            }


            //If no caracter can be printed in the next line then a new page is inserted
            if ((CurrentY + InternalTextHeight) >
                ConvertFromPixelsY(ConvertToPixelsY(Height, ScaleModeConstants.VbTwips)))
                NewPage();
        }
Esempio n. 16
0
        public async Task SendNotifyAsync(FormInfo formInfo, List <TableStyle> styles, DataInfo dataInfo)
        {
            if (formInfo.IsAdministratorSmsNotify &&
                !string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyTplId) &&
                !string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyMobile))
            {
                var isSmsEnabled = await _smsManager.IsEnabledAsync();

                if (isSmsEnabled)
                {
                    var parameters = new Dictionary <string, string>();
                    if (!string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyKeys))
                    {
                        var keys = formInfo.AdministratorSmsNotifyKeys.Split(',');
                        foreach (var key in keys)
                        {
                            if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.Id)))
                            {
                                parameters.Add(key, dataInfo.Id.ToString());
                            }
                            else if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.CreatedDate)))
                            {
                                if (dataInfo.CreatedDate.HasValue)
                                {
                                    parameters.Add(key, dataInfo.CreatedDate.Value.ToString("yyyy-MM-dd HH:mm"));
                                }
                            }
                            else
                            {
                                var value = dataInfo.Get <string>(key);
                                parameters.Add(key, value);
                            }
                        }
                    }

                    await _smsManager.SendAsync(formInfo.AdministratorSmsNotifyMobile,
                                                formInfo.AdministratorSmsNotifyTplId, parameters);
                }
            }

            if (formInfo.IsAdministratorMailNotify &&
                !string.IsNullOrEmpty(formInfo.AdministratorMailNotifyAddress))
            {
                var isMailEnabled = await _mailManager.IsEnabledAsync();

                if (isMailEnabled)
                {
                    var templateHtml = await GetMailTemplateHtmlAsync();

                    var listHtml = await GetMailListHtmlAsync();

                    var keyValueList = new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("编号", dataInfo.Guid)
                    };
                    if (dataInfo.CreatedDate.HasValue)
                    {
                        keyValueList.Add(new KeyValuePair <string, string>("提交时间",
                                                                           dataInfo.CreatedDate.Value.ToString("yyyy-MM-dd HH:mm")));
                    }

                    foreach (var style in styles)
                    {
                        keyValueList.Add(new KeyValuePair <string, string>(style.DisplayName,
                                                                           dataInfo.Get <string>(style.AttributeName)));
                    }

                    var list = new StringBuilder();
                    foreach (var kv in keyValueList)
                    {
                        list.Append(listHtml.Replace("{{key}}", kv.Key).Replace("{{value}}", kv.Value));
                    }

                    var subject  = !string.IsNullOrEmpty(formInfo.AdministratorMailTitle) ? formInfo.AdministratorMailTitle : "[SSCMS] 通知邮件";
                    var htmlBody = templateHtml
                                   .Replace("{{title}}", formInfo.Title)
                                   .Replace("{{list}}", list.ToString());

                    await _mailManager.SendAsync(formInfo.AdministratorMailNotifyAddress, subject,
                                                 htmlBody);
                }
            }

            if (formInfo.IsUserSmsNotify &&
                !string.IsNullOrEmpty(formInfo.UserSmsNotifyTplId) &&
                !string.IsNullOrEmpty(formInfo.UserSmsNotifyMobileName))
            {
                var isSmsEnabled = await _smsManager.IsEnabledAsync();

                if (isSmsEnabled)
                {
                    var parameters = new Dictionary <string, string>();
                    if (!string.IsNullOrEmpty(formInfo.UserSmsNotifyKeys))
                    {
                        var keys = formInfo.UserSmsNotifyKeys.Split(',');
                        foreach (var key in keys)
                        {
                            if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.Id)))
                            {
                                parameters.Add(key, dataInfo.Id.ToString());
                            }
                            else if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.CreatedDate)))
                            {
                                if (dataInfo.CreatedDate.HasValue)
                                {
                                    parameters.Add(key, dataInfo.CreatedDate.Value.ToString("yyyy-MM-dd HH:mm"));
                                }
                            }
                            else
                            {
                                var value = dataInfo.Get <string>(key);
                                parameters.Add(key, value);
                            }
                        }
                    }

                    var mobile = dataInfo.Get <string>(formInfo.UserSmsNotifyMobileName);
                    if (!string.IsNullOrEmpty(mobile))
                    {
                        await _smsManager.SendAsync(mobile, formInfo.UserSmsNotifyTplId, parameters);
                    }
                }
            }
        }
Esempio n. 17
0
        private static (object, int) DecodeObject(string str, Type type, int startPos)
        {
            var currChar = str[startPos];

            if (currChar != '{')
            {
                throw new Exception($"pos = {startPos} str = {str} not {{");
            }
            if (type.IsGenericType)
            {
                return(DecodeDict(str, type, startPos));
            }
            List <DataInfo> list = new List <DataInfo>();

            foreach (var item in type.GetMembers())
            {
                if (item.MemberType == MemberTypes.Field)
                {
                    list.Add(new DataInfo(DataInfo.Type__.Field, item));
                }
                else
                if (item.MemberType == MemberTypes.Property && (item as PropertyInfo).CanWrite)
                {
                    list.Add(new DataInfo(DataInfo.Type__.Property, item));
                }
            }
            object t = Activator.CreateInstance(type);

            startPos++;
            while (true)
            {
                AvoidLoopOver();
                startPos = DecodeSpace(str, startPos);
                currChar = str[startPos];
                if (currChar == '}')
                {
                    return(t, startPos + 1);
                }
                else
                if (currChar == ',')
                {
                    startPos = DecodeSpace(str, startPos + 1);
                }
                object key;
                (key, startPos) = DecodeString(str, startPos);
                startPos        = DecodeSpace(str, startPos);
                if (str[startPos] == ':')
                {
                    startPos++;
                }
                else
                {
                    throw new Exception($@"cann't decode the str not ':' in pos = {startPos} str = {str} char = {str[startPos]} 
                    string = {str.Substring(Math.Max(0, startPos - 10), startPos - Math.Max(0, startPos - 10) + 1)}");
                }
                string keyStr = key as string;
                startPos = DecodeSpace(str, startPos);
                if (keyStr.Equals("_t", StringComparison.Ordinal))
                {
                    (_, startPos) = DecodeString(str, startPos);
                }
                else
                {
                    DataInfo fieldInfo = DataInfo.Empty;
                    foreach (var item in list)
                    {
                        if (item.Name == keyStr)
                        {
                            fieldInfo = item;
                            break;
                        }
                    }
                    if (fieldInfo != DataInfo.Empty)
                    {
                        object value;
                        (value, startPos) = ToObject(str, startPos, fieldInfo.Type);
                        fieldInfo.SetData(t, value);
                    }
                }
            }
        }
Esempio n. 18
0
 public override void AddDataLine(DataInfo dataInfo)
 {
     if (_IsCollectingData)
         if (!_rawDataColl.TryAdd(dataInfo, AppConfiguration.DataLineProcessTimeout))
             _logger.LogError("Not able to add data line to Calibration data collection");
 }
Esempio n. 19
0
 public void AddDataLine(DataInfo dataInfo)
 {
     _rawDataColl.TryAdd(dataInfo, AppConfiguration.DataLineProcessTimeout);
 }
Esempio n. 20
0
        private static async void GetCrawling()
        {
            DataInfo.Add("SchoolNotice", new Dictionary <string, string>());
            DataInfo.Add("SchoolNewsletter", new Dictionary <string, string>());

            while (true)
            {
                try
                {
                    Logger.LogInformation("<Server> 학교 홈페이지 크롤링: 학교 공지사항을 가져옵니다.");
                    var tmpSchoolNotice = GetSchoolNotice();

                    Logger.LogInformation("<Server> 가정통신문 크롤링: 학교 공지사항을 가져옵니다.");
                    var tmpSchoolNewsletter = GetSchoolNewsletter();

                    if (tmpSchoolNotice != null)
                    {
                        // 학교 공지사항 데이터 값의 변화가 있는지 확인
                        if (SchoolNotice != null)
                        {
                            if (!JsonCompare(tmpSchoolNotice, SchoolNotice))
                            {
                                SchoolNotice = tmpSchoolNotice;

                                DataInfo["SchoolNotice"].Remove("LastUpdate");
                                DataInfo["SchoolNotice"].Add("LastUpdate", DateTime.Now.ToString());

                                DataInfo["SchoolNotice"].Remove("Size");
                                DataInfo["SchoolNotice"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpSchoolNotice)).ToString());
                            }
                        }
                        else
                        {
                            SchoolNotice = tmpSchoolNotice;

                            DataInfo["SchoolNotice"].Add("LastUpdate", DateTime.Now.ToString());
                            DataInfo["SchoolNotice"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpSchoolNotice)).ToString());
                        }
                    }
                    else
                    {
                        continue;
                    }

                    if (tmpSchoolNewsletter != null)
                    {
                        // 가정통신문 데이터 값의 변화가 있는지 확인
                        if (SchoolNewsletter != null)
                        {
                            if (!JsonCompare(tmpSchoolNewsletter, SchoolNewsletter))
                            {
                                SchoolNewsletter = tmpSchoolNewsletter;

                                DataInfo["SchoolNewsletter"].Remove("LastUpdate");
                                DataInfo["SchoolNewsletter"].Add("LastUpdate", DateTime.Now.ToString());

                                DataInfo["SchoolNewsletter"].Remove("Size");
                                DataInfo["SchoolNewsletter"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpSchoolNewsletter)).ToString());
                            }
                        }
                        else
                        {
                            SchoolNewsletter = tmpSchoolNewsletter;

                            DataInfo["SchoolNewsletter"].Add("LastUpdate", DateTime.Now.ToString());
                            DataInfo["SchoolNewsletter"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpSchoolNewsletter)).ToString());
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError("<Server> 학교 홈페이지 크롤링: 오류 (" + e.Message + ")");
                    continue;
                }

                await Task.Delay(1800000); // 1000 = 1초, 기본: 30분 (1800000)
            }
        }
Esempio n. 21
0
 public BuilderHelper()
 {
     Xml = new XmlInfo();
     Data = new DataInfo();
 }
Esempio n. 22
0
        public static List <string> MakeBlazer(DataInfo info,
                                               Options options)
        {
            List <string> stringResult = new List <string>();
            List <string> stringFile   = info.HtmlStrings;
            List <string> stringWork;

            bool ignoreScript = false;
            bool stripScript  = false;
            bool inside;

            if ((options.SelectedScriptOptions == Script_Options.IgnoreScript))
            {
                ignoreScript = true;
            }
            else if ((options.SelectedScriptOptions == Script_Options.StripMultiLine))
            {
                stripScript = true;
            }
            else if ((options.SelectedScriptOptions == Script_Options.All))
            {
                stripScript = true;
            }

            string str = "@page " + Support.Quote("/" + options.PageName);

            stringResult.Add(str);
            stringResult.Add("");

            string stringDivStyle = "";

            if (options.SelectedRazorOptions == Page_Options.ConvertBodyStyleBackground)
            {
                stringDivStyle = ConvertBodyStyleToDivStyle(stringFile);
                if (stringDivStyle.Length > 0)
                {
                    stringResult.Add(stringDivStyle);
                }
            }
            if (options.IsTraceOn(Trace_Options.TraceInfo))
            {
                Trace.TraceInformation("first part of scripts");
            }

            if (stripScript == true)
            {
                stringWork = new List <string>();
                bool insideScript = false;
                foreach (string s in stringFile)
                {
                    if ((s.Contains("script>") == true) &&
                        (s.Contains(@"<script") == false))
                    {
                        insideScript = false;
                    }
                    else if ((s.Contains(@"<script") == true) &&
                             (s.Contains("script>") == false))
                    {
                        insideScript = true;
                    }
                    else if (insideScript == false)
                    {
                        if (options.IsTraceOn(Trace_Options.TraceInfo))
                        {
                            Trace.TraceInformation(s);
                        }
                        stringWork.Add(s);
                    }
                }
            }
            else
            {
                stringWork = stringFile;
            }

            if (options.IsTraceOn(Trace_Options.TraceInfo))
            {
                Trace.TraceInformation("second part of scripts");
            }

            inside = false;
            foreach (string s in stringWork)
            {
                if (inside == true)
                {
                    if (s.Contains(@"</body>") == true)
                    {
                        inside = false;
                    }
                    else if ((ignoreScript == true) ||
                             (s.Contains("script>") == false))
                    {
                        if (options.IsTraceOn(Trace_Options.TraceInfo))
                        {
                            Trace.TraceInformation(s);
                        }
                        stringResult.Add(s);
                    }
                }
                else if (s.Contains("<body") == true)
                {
                    inside = true;
                }
            }

            if (stringDivStyle.Length > 0)
            {
                stringResult.Add("</div>");
            }

            stringResult.Add("");
            stringResult.Add("@code {");
            stringResult.Add("");
            stringResult.Add("}");

            return(stringResult);
        }
Esempio n. 23
0
        public static List <Asset> MakeScriptAssets(DataInfo info,
                                                    Options options)
        {
            List <string> stringFile = info.HtmlStrings;
            List <string> stringWork;
            List <Asset>  assetList    = new List <Asset>();
            bool          scriptToHost = false;
            bool          inside       = false;
            Asset         asset;

            if ((options.SelectedScriptOptions == Script_Options.SelectedScriptToHost))
            {
                scriptToHost = true;
            }
            else if (options.SelectedScriptOptions == Script_Options.All)
            {
                scriptToHost = true;
            }

            if (scriptToHost == true)
            {
                if (options.IsTraceOn(Trace_Options.TraceInfo))
                {
                    Trace.TraceInformation("Script to host, remove embedded scripts");
                }

                int count = 0;
                stringWork = new List <string>();
                bool insideScript = false;
                foreach (string s in stringFile)
                {
                    if ((s.Contains("script>") == true) &&
                        (s.Contains(@"<script") == false))
                    {
                        count++;
                        insideScript = false;
                    }
                    else if ((s.Contains(@"<script") == true) &&
                             (s.Contains("script>") == false))
                    {
                        insideScript = true;
                    }
                    else if (insideScript == false)
                    {
                        if (options.IsTraceOn(Trace_Options.TraceInfo))
                        {
                            Trace.TraceInformation(s);
                        }
                        stringWork.Add(s);
                    }
                }
                info.MultiLineScriptCount = count;

                if (options.IsTraceOn(Trace_Options.TraceInfo))
                {
                    Trace.TraceInformation("Start AssetList");
                }

                foreach (string s in stringWork)
                {
                    if (inside == true)
                    {
                        if (options.IsTraceOn(Trace_Options.TraceInfo))
                        {
                            Trace.TraceInformation(s);
                        }
                        if ((s.Contains("<script")) && (s.Contains("script>")))
                        {
                            info.ScriptAssets.Add(s);
                        }
                        if (s.Contains(@"</body>") == true)
                        {
                            inside = false;
                        }
                        else if ((s.Contains(@"<script") == true) &&
                                 (s.Contains("script>") == true) &&
                                 (scriptToHost == true))
                        {
                            asset = AddScriptToHostAsset(options, s);
                            if (asset != null)
                            {
                                assetList.Add(asset);
                            }
                        }
                    }
                    else if (s.Contains("<body") == true)
                    {
                        inside = true;
                    }
                }
            }
            if (options.IsTraceOn(Trace_Options.TraceInfo))
            {
                Trace.TraceInformation("End AssetList");
            }

            return(assetList);
        }
Esempio n. 24
0
        // private methods

        public static List <string> MakePreview(Options options,
                                                DataInfo info)
        {
            List <string> stringsResult = new List <string>();
            string        str;

            if (info.IsBootstrapHtml == true)
            {
                str = "Bootstrap HTML Project Path = " + options.BootstrapProjectPath;
            }
            else
            {
                str = "HTML (other)   Project Path = " + options.BootstrapProjectPath;
            }
            stringsResult.Add(str);
            str = "Project Path                = " + options.BlazorProjectPath;
            stringsResult.Add(str);
            stringsResult.Add("");


            str = "SelectedModifyOptions     = " + options.SelectedModifyOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedAssetOptions      = " + options.SelectedAssetOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedCSSptions         = " + options.SelectedCSSOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedHostOptions       = " + options.SelectedHostOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedScriptOptions     = " + options.SelectedScriptOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedNavMenuOptions    = " + options.SelectedNavMenuOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedRazorOptions      = " + options.SelectedRazorOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedTraceOptions      = " + options.SelectedTraceOptions.ToString();
            stringsResult.Add(str);
            str = "SelectedRenderModeOptions = " + options.SelectedRenderModeOptions.ToString();
            stringsResult.Add(str);
            stringsResult.Add("");



            if (info.ProjectType == Type_Options.BlazorServer)
            {
                str = "Preview for Blazor Page " + options.PageName + " in file " + GetRazorFile(options, info);
            }
            else if (info.ProjectType == Type_Options.BlazorWebassembly)
            {
                str = "Preview for Blazor Webassembly Page " + options.PageName + " in file " + GetRazorFile(options, info);
            }
            else if (info.ProjectType == Type_Options.BlazorWebassemblyPWA)
            {
                str = "Preview for Blazor Webassembly PWA Page " + options.PageName + " in file " + GetRazorFile(options, info);
            }
            else if (info.ProjectType == Type_Options.ASPNetRazor)
            {
                str = "Preview for ASP.Net Razor Page " + options.PageName + " in file " + GetRazorFile(options, info);
            }
            else
            {
                str = "Unknown Type Preview";
            }

            stringsResult.Add(str);
            stringsResult.Add("");

            // first output blazor page
            foreach (string s in info.BlazorStrings)
            {
                stringsResult.Add(s);
            }
            stringsResult.Add("");

            if (info.RazorCodeBehindStrings.Count > 0)
            {
                str = "Preview of Razor Code behind strings in " + options.BlazorProjectPath + "Pages//" + options.PageName + ".cshtml.cs";
                stringsResult.Add(str);
                stringsResult.Add("");

                // output razor code behind page
                foreach (string s in info.RazorCodeBehindStrings)
                {
                    stringsResult.Add(s);
                }
                stringsResult.Add("");
            }

            if (info.HostAssetsStrings.Count > 0)
            {
                str = "Preview for changes in " + GetHostFile(options, info);
                stringsResult.Add(str);
                stringsResult.Add("");

                foreach (string s in info.HostAssetsStrings)
                {
                    stringsResult.Add(s);
                }
                stringsResult.Add("");
            }

            if (info.HostRenderMode.Length > 0)
            {
                stringsResult.Add("");
                str = "    " + info.HostRenderMode;
                stringsResult.Add(str);
                stringsResult.Add("");
            }

            if (info.NewHostStrings.Count > 0)
            {
                str = "Preview for Host Changes in " + GetHostFile(options, info);
                stringsResult.Add(str);
                stringsResult.Add("");

                foreach (string s in info.NewHostStrings)
                {
                    stringsResult.Add(s);
                }
                stringsResult.Add("");
            }

            if ((info.ProjectType == Type_Options.ASPNetRazor) &&
                (info.RazorCustomLayoutStrings.Count > 0))
            {
                str = "Preview for Razor Custom Layout Changes in " + GetRazorCustomLayoutFile(options, info);
                stringsResult.Add(str);
                stringsResult.Add("");

                foreach (string s in info.RazorCustomLayoutStrings)
                {
                    stringsResult.Add(s);
                }
                stringsResult.Add("");
            }

            if (options.SelectedNavMenuOptions != NavMenu_Options.None)
            {
                if (info.NewNavMenuStrings.Count > 0)
                {
                    if (info.ProjectType == Type_Options.ASPNetRazor)
                    {
                        str = "Preview for Razor NavMenu Changes in" + GetNavMenuFile(options, info);
                    }
                    else
                    {
                        str = "Preview for NavMenu.Razor Changes in" + GetNavMenuFile(options, info);
                    }
                    stringsResult.Add(str);
                    stringsResult.Add("");

                    foreach (string s in info.NewNavMenuStrings)
                    {
                        stringsResult.Add(s);
                    }
                    stringsResult.Add("");
                }
            }

            stringsResult.Add("Scripts assets");
            stringsResult.Add("  Total Multi-Line Scripts detected: " + info.MultiLineScriptCount.ToString());
            stringsResult.Add("  Total External   Scripts detected: " + info.ScriptAssets.Count.ToString());
            foreach (string s in info.ScriptAssets)
            {
                stringsResult.Add("       " + s);
            }
            stringsResult.Add("");



            stringsResult.Add("Asset List");
            stringsResult.Add("");
            foreach (Asset ThisAsset in info.Assets)
            {
                str = "   Index=" + ThisAsset.Index.ToString() + "   " + ThisAsset.AssetType.ToString();
                stringsResult.Add(str);
                str = "   HtmlAsset=[" + ThisAsset.HtmlAsset + "]   RawAssset=[" + ThisAsset.RawAsset + "]";
                stringsResult.Add(str);
            }
            stringsResult.Add("");

            if ((options.SelectedHostOptions != Host_Options.None) &&
                (options.HostAssetsDirectory.Length > 0))
            {
                string sourceDirectory      = GetSourceDirectory(options);
                string destinationDirectory = GetDestinationDirectory(options);

                stringsResult.Add("Will copy Assets Source=" + sourceDirectory);
                stringsResult.Add("                 Dest  =" + destinationDirectory);
                stringsResult.Add("");
            }

            return(stringsResult);
        }
Esempio n. 25
0
        public static List <string> MakeRazor(DataInfo info,
                                              Options options)
        {
            List <string> stringsResult = new List <string>();
            List <string> stringsFile   = info.HtmlStrings;

            string str = "@page";

            stringsResult.Add(str);
            str = "@model " + options.PageName + "Model";
            stringsResult.Add(str);
            str = "@{";
            stringsResult.Add(str);
            str = "    ViewData[" + Support.Quote("Title") + "] = " + Support.Quote(options.PageName) + ";";
            stringsResult.Add(str);
            if (options.MakeCustomRazorLayout == true)
            {
                str = "    Layout=" + Support.Quote(options.PageName + "_Layout.cshtml") + ";";
                stringsResult.Add(str);
                stringsResult.Add("");
            }
            str = "}";
            stringsResult.Add(str);
            stringsResult.Add("");
            str = "<h1>@ViewData[" + Support.Quote("Title") + "]</h1>";
            stringsResult.Add(str);
            stringsResult.Add("");

            string stringDivStyle = "";

            if (options.SelectedRazorOptions == Page_Options.ConvertBodyStyleBackground)
            {
                stringDivStyle = ConvertBodyStyleToDivStyle(stringsFile);
                if (stringDivStyle.Length > 0)
                {
                    stringsResult.Add(stringDivStyle);
                }
            }

            bool inside = false;

            foreach (string s in stringsFile)
            {
                if (inside == true)
                {
                    if (s.Contains(@"</body>") == true)
                    {
                        inside = false;
                    }
                    else if ((options.SelectedScriptOptions != Script_Options.IgnoreScript) ||
                             (s.Contains("script>") == false))
                    {
                        str = IsRazorScriptAllowed(s);
                        if (string.IsNullOrEmpty(str) == false)
                        {
                            stringsResult.Add(str);
                        }
                    }
                }
                else if (s.Contains("<body") == true)
                {
                    inside = true;
                }
            }

            if (stringDivStyle.Length > 0)
            {
                stringsResult.Add("</div>");
            }

            stringsResult.Add("");

            return(stringsResult);
        }
Esempio n. 26
0
        public static DataInfo CreateDataInfo(Options options)
        {
            DataInfo info = new DataInfo();

            if (options.IsUseSameIndexAssets() == false)
            {
                options.IndexPageName = options.PageName;
            }

            info.ProjectType   = GetProjectType(options);
            info.HtmlStrings   = MakeHtml(options);
            info.HostStrings   = MakeHostHtml(info, options);
            info.AssetsStrings = MakeAssets(info, options);
            info.Assets        = MakeScriptAssets(info, options);

            if (options.IsUseMoveAssets() == true)
            {
                info.Assets      = CreateMoveAssets(info, options);
                info.HtmlStrings = AdjustHtmlForMoveAssets(info, options);
            }

            if (info.ProjectType == Type_Options.ASPNetRazor)
            {
                options.RazorNameSpace        = GetRazorNameSpace(options);
                info.BlazorStrings            = MakeRazor(info, options);
                info.RazorCodeBehindStrings   = MakeRazorCodeBehind(options);
                info.HostAssetsStrings        = MakeHostAssets(info, options);
                info.NewHostStrings           = MakeNewHostStrings(info);
                info.NavMenuStrings           = MakeRazorNavMenuStrings(options);
                info.NewNavMenuStrings        = MakeNewNavMenuStrings(info, options);
                info.RazorAssetsStrings       = MakeRazorHostAssets(info, options);
                info.RazorCustomLayoutStrings = MakeRazorCustomLayoutString(info, options);

                UpdateBlazorForAssets(info, options);
                if (info.HasScriptAsset() == true)
                {
                    info.RazorCustomLayoutStrings = AdjustRazorCustomLayoutForScriptAssets(info, options);
                }
            }
            else
            {
                info.BlazorStrings     = MakeBlazer(info, options);
                info.HostAssetsStrings = MakeHostAssets(info, options);
                info.HostRenderMode    = MakeHostRenderMode(info, options);
                info.NewHostStrings    = MakeNewHostStrings(info);
                info.NavMenuStrings    = MakeNavMenuStrings(options);
                info.NewNavMenuStrings = MakeNewNavMenuStrings(info, options);

                UpdateBlazorForAssets(info, options);
                if (info.HasScriptAsset() == true)
                {
                    info.NewHostStrings = AdjustForScriptAssets(info, options);
                }
            }



            if (options.HasPreview() == true)
            {
                options.PreviewFile = options.BlazorProjectPath + options.PageName + "_preview.txt";
                info.PreviewStrings = MakePreview(options, info);
            }
            info.UpdateGenerateStatus();
            return(info);
        }
Esempio n. 27
0
        /// <summary>
        /// the function send request from the server to the set config
        /// </summary>
        public void getFirstConfi()
        {
            DataInfo msg = new DataInfo(CommandEnum.GetConfigCommand, null);

            clientConnection.WriteToServer(msg.toJson());
        }
Esempio n. 28
0
 public void AddDataLine(ref DataInfo dataInfo)
 {
     _inComingDataColl.TryAdd(dataInfo, AppConfiguration.DataLineProcessTimeout);
 }
Esempio n. 29
0
 public virtual void AddDarkDataLine(DataInfo dataInfo)
 {
 }
Esempio n. 30
0
        public static List <string> MakeAssets(DataInfo info,
                                               Options options)
        {
            List <string> stringsResult = new List <string>();

            foreach (string s in info.HtmlStrings)
            {
                if (s.Contains("stylesheet") == true)
                {
                    if (s.Contains(@"assets/css") == true)
                    {
                        if (options.IsTraceOn(Trace_Options.TraceInfo))
                        {
                            Trace.TraceInformation(s);
                        }
                        stringsResult.Add(s);
                    }
                    else if (s.Contains(@"assets/fonts") == true)
                    {
                        if (options.IsTraceOn(Trace_Options.TraceInfo))
                        {
                            Trace.TraceInformation(s);
                        }
                        stringsResult.Add(s);
                    }
                    else if (s.Contains(@"https://fonts") == true)
                    {
                        if (options.IsCSSFontOption() == true)
                        {
                            if (options.IsTraceOn(Trace_Options.TraceInfo))
                            {
                                Trace.TraceInformation(s);
                            }
                            stringsResult.Add(s);
                        }
                    }
                    else if ((s.Contains("bootstrap") == true) &&
                             (s.Contains("https") == false))
                    {
                        if (options.IsCSSBootstrapOption() == true)
                        {
                            if (options.IsTraceOn(Trace_Options.TraceInfo))
                            {
                                Trace.TraceInformation(s);
                            }
                            stringsResult.Add(s);
                        }
                    }
                    else if ((s.Contains("https") == true) &&
                             (s.Contains("aos.css") == true))
                    {
                        if (options.IsCSSAOSOption() == true)
                        {
                            if (options.IsTraceOn(Trace_Options.TraceInfo))
                            {
                                Trace.TraceInformation(s);
                            }
                            stringsResult.Add(s);
                        }
                    }
                }
            }
            return(stringsResult);
        }
Esempio n. 31
0
 public void DoContextData(DataInfo info)
 {
 }
Esempio n. 32
0
        public static List <string> AdjustForScriptAssets(DataInfo info,
                                                          Options options)
        {
            string        str;
            List <string> stringsResult = new List <string>();

            foreach (string s in info.NewHostStrings)
            {
                if (s.Contains(@"</body>") == true)
                {
                    if (info.HasScriptAsset() == true)
                    {
                        if (info.ProjectType == Type_Options.BlazorServer)
                        {
                            str = "    @if(Request.Path.Value == " + Support.Quote(@"/" + options.PageName) + ")";
                            stringsResult.Add(str);
                            if (options.IsTraceOn(Trace_Options.TraceInfo))
                            {
                                Trace.TraceInformation(str);
                            }
                            str = "    {";
                            stringsResult.Add(str);
                            if (options.IsTraceOn(Trace_Options.TraceInfo))
                            {
                                Trace.TraceInformation(str);
                            }
                            foreach (Asset asset in info.Assets)
                            {
                                if (asset.IsScriptAsset() == true)
                                {
                                    str = asset.HtmlAsset;
                                    if (str.Contains("assets") == true)
                                    {
                                        str = str.Replace("assets", options.PageName + @"/assets");
                                    }
                                    str = "        " + str;
                                    stringsResult.Add(str);
                                    if (options.IsTraceOn(Trace_Options.TraceInfo))
                                    {
                                        Trace.TraceInformation(str);
                                    }
                                }
                            }

                            str = "    }";
                            stringsResult.Add(str);
                            if (options.IsTraceOn(Trace_Options.TraceInfo))
                            {
                                Trace.TraceInformation(str);
                            }
                        }
                        else if (options.IsUseSharedAssets() == true)
                        {
                            foreach (Asset asset in info.Assets)
                            {
                                if (asset.IsScriptAsset() == true)
                                {
                                    str = asset.HtmlAsset;
                                    stringsResult.Add(str);
                                    if (options.IsTraceOn(Trace_Options.TraceInfo))
                                    {
                                        Trace.TraceInformation(str);
                                    }
                                }
                            }
                        }
                    }
                }
                stringsResult.Add(s);
                if (options.IsTraceOn(Trace_Options.TraceInfo))
                {
                    Trace.TraceInformation(s);
                }
            }

            return(stringsResult);
        }
Esempio n. 33
0
        public bool GetData(string fileName, ref string strErrMsg)
        {
            string strTemp;

            if (File.Exists(fileName) == false)
            {
                strErrMsg = "file :" + dataFile + "not exists";
                return(false);
            }

            FileStream   fs           = new FileStream(dataFile, FileMode.Open);
            StreamReader streamReader = new StreamReader(fs);

            int      iline        = 1;
            int      iOffset      = 0;
            string   strKey       = "";
            DataInfo dataInfoTemp = new DataInfo();

            while ((strTemp = streamReader.ReadLine()) != null)
            {
                strKey  = string.Format("{0}{1}{2}", DataInfoKeyStr.HeadKey, iline, "={");
                iOffset = strTemp.IndexOf(strKey);
                if (iOffset < 0)
                {
                    strErrMsg = "first line head key error";
                    return(false);
                }

                dataInfoTemp.A = "0";
                dataInfoTemp.B = "0";
                dataInfoTemp.C = "0";
                dataInfoTemp.X = "0";
                dataInfoTemp.Y = "0";
                dataInfoTemp.Z = "0";

                dataInfoTemp.E1 = "0";
                dataInfoTemp.E2 = "0";
                dataInfoTemp.E3 = "0";
                dataInfoTemp.E4 = "0";
                dataInfoTemp.E5 = "0";
                dataInfoTemp.E6 = "0";
                dataInfoTemp.S  = "0";
                dataInfoTemp.T  = "0";

                strTemp = strTemp.Replace(strKey, "");
                if (GetEachLineData(ref dataInfoTemp, strTemp) == false)
                {
                    return(false);
                }

                dataInfo[iline - 1].X = dataInfoTemp.X;
                dataInfo[iline - 1].Y = dataInfoTemp.Y;
                dataInfo[iline - 1].Z = dataInfoTemp.Z;

                dataInfo[iline - 1].A = dataInfoTemp.A;
                dataInfo[iline - 1].B = dataInfoTemp.B;
                dataInfo[iline - 1].C = dataInfoTemp.C;

                dataInfo[iline - 1].S = dataInfoTemp.S;
                dataInfo[iline - 1].T = dataInfoTemp.T;

                dataInfo[iline - 1].E1 = dataInfoTemp.E1;
                dataInfo[iline - 1].E2 = dataInfoTemp.E2;
                dataInfo[iline - 1].E3 = dataInfoTemp.E3;
                dataInfo[iline - 1].E4 = dataInfoTemp.E4;
                dataInfo[iline - 1].E5 = dataInfoTemp.E5;
                dataInfo[iline - 1].E6 = dataInfoTemp.E6;

                iline++;
            }
            streamReader.Close();
            fs.Close();
            return(true);
        }
Esempio n. 34
0
        public IHttpActionResult Apply()
        {
            try
            {
                var request = Context.AuthenticatedRequest;
                var siteId  = request.GetQueryInt("siteId");

                var provideType    = request.GetPostObject <List <string> >("provideType");
                var obtainType     = request.GetPostObject <List <string> >("obtainType");
                var departmentId   = request.GetPostInt("departmentId");
                var departmentInfo = DepartmentManager.GetDepartmentInfo(siteId, departmentId);

                var dataInfo = new DataInfo
                {
                    Id                = 0,
                    SiteId            = siteId,
                    AddDate           = DateTime.Now,
                    QueryCode         = StringUtils.GetShortGuid(true),
                    DepartmentId      = departmentInfo?.Id ?? 0,
                    IsCompleted       = false,
                    State             = DataState.New.Value,
                    DenyReason        = string.Empty,
                    RedoComment       = string.Empty,
                    ReplyContent      = string.Empty,
                    IsReplyFiles      = false,
                    ReplyDate         = DateTime.Now,
                    IsOrganization    = request.GetPostBool("isOrganization"),
                    CivicName         = request.GetPostString("civicName"),
                    CivicOrganization = request.GetPostString("civicOrganization"),
                    CivicCardType     = request.GetPostString("civicCardType"),
                    CivicCardNo       = request.GetPostString("civicCardNo"),
                    CivicPhone        = request.GetPostString("civicPhone"),
                    CivicPostCode     = request.GetPostString("civicPostCode"),
                    CivicAddress      = request.GetPostString("civicAddress"),
                    CivicEmail        = request.GetPostString("civicEmail"),
                    CivicFax          = request.GetPostString("civicFax"),
                    OrgName           = request.GetPostString("orgName"),
                    OrgUnitCode       = request.GetPostString("orgUnitCode"),
                    OrgLegalPerson    = request.GetPostString("orgLegalPerson"),
                    OrgLinkName       = request.GetPostString("orgLinkName"),
                    OrgPhone          = request.GetPostString("orgPhone"),
                    OrgPostCode       = request.GetPostString("orgPostCode"),
                    OrgAddress        = request.GetPostString("orgAddress"),
                    OrgEmail          = request.GetPostString("orgEmail"),
                    OrgFax            = request.GetPostString("orgFax"),
                    Title             = request.GetPostString("title"),
                    Content           = request.GetPostString("content"),
                    Purpose           = request.GetPostString("purpose"),
                    IsApplyFree       = request.GetPostBool("isApplyFree"),
                    ProvideType       = TranslateUtils.ObjectCollectionToString(provideType),
                    ObtainType        = TranslateUtils.ObjectCollectionToString(obtainType),
                    DepartmentName    = departmentInfo == null ? string.Empty : departmentInfo.DepartmentName
                };

                Main.DataRepository.Insert(dataInfo);

                return(Ok(new
                {
                    Value = dataInfo
                }));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Esempio n. 35
0
 protected override void Because()
 {
     _clone = sut.Clone();
 }
Esempio n. 36
0
        public static void GeneralReadFrom(MethodBuilder sink, DataInfo info,
                                           Action <MethodBuilder, DataInfo> baseReadCall, string isNullReader, string classIdReader,
                                           string directReader, string refInst, string refIdReader, bool pooled, Func <Type, string> configIdReader = null, bool needCreateVar = false,
                                           bool useTempVarThenAssign = false, bool getDataNodeFromRootWithRefId = false)
        {
            var t         = info.type;
            var canBeNull = info.canBeNull && !t.IsValueType;

            var    originalInfo = info;
            string tempVar      = "__" + originalInfo.baseAccess.Replace("[", "").Replace("]", "");

            if (useTempVarThenAssign)
            {
                sink.content($"var {tempVar} = {originalInfo.access};");
                info = new DataInfo
                {
                    type       = originalInfo.type,
                    baseAccess = tempVar,
                };
            }

            var  name          = info.access;
            bool newInstCalled = false;

            if (needCreateVar)
            {
                sink.content($"{info.type.RealName(true)} {info.name} = default;");
            }

            if (t.IsImmutableValueType() || t.IsValueType && t.IsControllable() == false)
            {
                sink.content($"{name} = {directReader};");
                return;
            }
            else if (t.IsRef())
            {
                if (CodeGenTools.Valid(refIdReader))
                {
                    sink.content($"{info.access}.id = {refIdReader};");
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            else
            {
                if (canBeNull)
                {
                    sink.content($"if ({isNullReader}) {{");
                    sink.indent++;
                    SinkRemovePostProcess(sink, info, pooled);
                    sink.content($"{name} = null;");
                    sink.indent--;
                    sink.content($"}}");
                    sink.content($"else {{ ");
                    sink.indent++;
                }

                bool fromExternalSource = false;
                if (t.IsConfig() && info.insideConfigStorage == false)
                {
                    ConfigFromId(sink, info, configIdReader, false);
                    fromExternalSource = true;
                }
                else if (getDataNodeFromRootWithRefId && typeof(IReferencableFromDataRoot).IsAssignableFrom(t))
                {
                    sink.content($"{info.access} = ({info.type.RealName(true)})root.Recall({refIdReader});");
                    fromExternalSource = true;
                }
                else
                {
                    if (info.sureIsNull && !info.type.IsValueType)
                    {
                        CreateNewInstance(sink, info, classIdReader, pooled, refInst, false);
                        newInstCalled = true;
                    }
                    else
                    {
                        string createNewCondition = "";
                        if (canBeNull || info.CanBeNullAfterConstruction())
                        {
                            createNewCondition = $"{name} == null";
                        }

                        string classIdVarName = $"{name.Replace('[', '_').Replace(']', '_').Replace('.', '_')}ClassId";
                        if (t.CanBeAncestor() && info.cantBeAncestor == false)
                        {
                            sink.content($"var {classIdVarName} = {classIdReader};");
                            createNewCondition = AddOrCondition(createNewCondition,
                                                                $"{name}.{PolymorphClassIdGetter} != {classIdVarName}");
                        }
                        if (info.type.IsImmutableType() == false && CodeGenTools.Valid(createNewCondition))
                        {
                            sink.content($"if ({createNewCondition}) {{");
                            sink.indent++;
                            SinkRemovePostProcess(sink, info, pooled);
                            CreateNewInstance(sink, info, classIdVarName, pooled, refInst, false);
                            newInstCalled = true;
                            sink.indent--;
                            sink.content($"}}");
                        }
                    }
                }

                if (!fromExternalSource)
                {
                    baseReadCall(sink, info);
                }

                if (canBeNull)
                {
                    sink.indent--;
                    sink.content($"}}");
                }
            }

            if (useTempVarThenAssign)
            {
                sink.content($"{originalInfo.access} = {tempVar};");
            }
        }
 public override void SetData(string key, string value, bool statusData,bool immediate)
 {
     DataInfo di = new DataInfo ();
     di.statusData = statusData;
     di.value = value;
     lock(_values)
     {
         if(!_values.ContainsKey(key))
             _values.Add(key,di);
         else _values[key]=di;
         _UpdateData(immediate);
     }
 }
Esempio n. 38
0
        protected override void processIncomingMessage(IncomingMessage message)
        {
            byte messageType = message.MessageType;

            if ((uint)messageType <= 9U)
            {
                switch (messageType)
                {
                case 1:
                    this.receiveServerIntroduction(message.Reader);
                    return;

                case 2:
                    this.userNames[message.FarmerID] = message.Reader.ReadString();
                    ModCore.multiplayer.processIncomingMessage(message);
                    return;

                case 3:
                    ModCore.multiplayer.processIncomingMessage(message);
                    return;

                case 9:
                    this.receiveAvailableFarmhands(message.Reader);
                    return;
                }
            }
            else if ((int)messageType != 11)
            {
                if ((int)messageType == 16)
                {
                    if (message.FarmerID != Game1.serverHost.Value.UniqueMultiplayerID)
                    {
                        return;
                    }
                    this.receiveUserNameUpdate(message.Reader);
                    return;
                }
            }
            else
            {
                this.connectionMessage = message.Reader.ReadString();
                return;
            }
            ModCore.multiplayer.processIncomingMessage(message);


            //Packet signiture for functions that return nothing.
            if (message.MessageType == Enums.MessageTypes.SendOneWay || message.MessageType == Enums.MessageTypes.SendToAll)
            {
                object[] obj          = message.Reader.ReadModdedInfoPacket();
                string   functionName = (string)obj[0];
                string   classType    = (string)obj[1];
                object   actualObject = ModCore.processTypesToRead(message.Reader, classType);
                ModCore.processVoidFunction(functionName, actualObject);
                return;
            }
            else
            {
                if (message.MessageType == Enums.MessageTypes.SendToSpecific)
                {
                    object[] obj          = message.Reader.ReadModdedInfoPacket();
                    string   functionName = (string)obj[0];
                    string   classType    = (string)obj[1];
                    object   actualObject = ModCore.processTypesToRead(message.Reader, classType);
                    DataInfo info         = (DataInfo)actualObject;

                    if (info.recipientID == Game1.player.UniqueMultiplayerID.ToString())
                    {
                        ModCore.processVoidFunction(functionName, actualObject);
                    }
                }
            }

            //message.Reader.ReadChar();
            //Write Binary ententions reader

            //ModCore.multiplayer.processIncomingMessage(message); //If we don't know how to initially process the message, send it to the multiplayer function.
        }
Esempio n. 39
0
 public void TestSetup()
 {
     _driver = Substitute.For <IStorageDriver>();
     _index  = Substitute.For <IStorageIndex>();
     _info   = new DataInfo("test data");
 }
Esempio n. 40
0
        /// <summary>
        /// 记录学习时间
        /// </summary>
        /// <param name="myLRecord">学习记录信息</param>
        /// <param name="workUser"></param>
        /// <returns></returns>
        public ReturnValueModel AddLearn(MyLRecord myLRecord, WorkUser workUser)
        {
            ReturnValueModel rvm    = new ReturnValueModel();
            int RemindOffsetMinutes = 0;

            try
            {
                /*
                 * 播客:传入学习时长、开始时间
                 * 其他:开始和结束时间
                 */
                if (myLRecord != null)
                {
                    myLRecord.Id          = Guid.NewGuid().ToString();
                    myLRecord.LDate       = DateTime.Now;
                    myLRecord.UnionId     = workUser.WxUser.UnionId;
                    myLRecord.CreateTime  = DateTime.Now;
                    myLRecord.LObjectDate = myLRecord.LObjectDate ?? 0;
                    myLRecord.WxUserId    = workUser.WxUser.Id;
                    switch (myLRecord.LObjectType)
                    {
                    case 1:    //文章
                    case 2:    //文档
                        myLRecord.LObjectDate = (int)(myLRecord.LDateEnd - myLRecord.LDateStart)?.TotalSeconds;
                        _rep.Insert(myLRecord);
                        _rep.SaveChanges();
                        break;

                    case 3:    //播客
                        _rep.Insert(myLRecord);
                        _rep.SaveChanges();
                        break;

                    case 4:    //视频
                        myLRecord.LObjectDate = (int)(myLRecord.LDateEnd - myLRecord.LDateStart)?.TotalSeconds;
                        _rep.Insert(myLRecord);
                        _rep.SaveChanges();
                        break;

                    case 5:    //会议
                        var meet = _rep.FirstOrDefault <MeetInfo>(s => s.Id == myLRecord.LObjectId);
                        //if (meet.MeetEndTime > myLRecord.LDate)
                        //{
                        myLRecord.LObjectDate = (int)(myLRecord.LDateEnd - myLRecord.LDateStart)?.TotalSeconds;

                        _rep.Insert(myLRecord);
                        _rep.SaveChanges();
                        //}
                        break;

                    case 9:

                        _rep.Insert(myLRecord);
                        _rep.SaveChanges();
                        break;

                    default:
                        break;
                    }
                }

                /*
                 * 知识库打开过后,点击量就增加
                 */
                if (myLRecord != null)
                {
                    string lObjectId = myLRecord.LObjectId;

                    DataInfo datainfo = _rep.Table <DataInfo>().Where(a => a.Id == lObjectId).FirstOrDefault();
                    if (datainfo != null)
                    {
                        datainfo.ClickVolume = datainfo.ClickVolume + 1;
                        _rep.Update(datainfo);
                        _rep.SaveChanges();
                    }
                }

                rvm.Msg     = "success";
                rvm.Success = true;
                return(rvm);
            }
            catch (Exception ex)
            {
                rvm.Msg     = "fail";
                rvm.Success = false;
                return(rvm);
            }
        }
Esempio n. 41
0
 public override void AddAirDataLine(DataInfo dataInfo)
 {
     _DataCollection.AddAirData(dataInfo.XRayInfo.Energy, dataInfo.LineData);
 }
Esempio n. 42
0
        //
        // GET: /Home/
        public ActionResult Index()
        {
            DataInfo Model          = new DataInfo();
            int      clientPlatform = 4;
            //viewLite viewLite = new viewLite { frameName = "EcrpSole", viewName = "ProfileTable" };
            viewLite viewLite = new viewLite {
                frameName = "EcrpMain", viewName = "AfficheTable"
            };
            sortInfo sortInfo = new sortInfo {
                sortType = 6
            };
            searchInfo searchInfo = new searchInfo {
                allowDrop = false, pageCount = 20, pageIndex = 1, sortInfo = sortInfo
            };;
            Dictionary <string, object> parameters = new Dictionary <string, object>();

            parameters.Add("clientPlatform", clientPlatform);
            parameters.Add("viewLite", viewLite);
            parameters.Add("searchInfo", searchInfo);
            string jsonStr   = ToJson.ScriptSerialize(parameters);
            string url       = "Http://61.155.203.29:60214/service.svc/ReadDatasBySearchInfo2";
            string resultStr = HttpCode.Post(url, jsonStr);
            Dictionary <string, object> obj = JsonTo.ScriptDeserialize(resultStr);
            string value = obj["value"].ToString();
            List <Dictionary <string, object> > val = JsonTo.ScriptDeserializeList(value);

            //Model.count = val.Count;
            Model.list = val;
            //foreach (Dictionary<string, object> s in val)
            //{
            //    Model.id = Convert.ToInt32(s["id"]);
            //    Model.uid = Convert.ToInt32(s["uid"]);
            //    Model.cid = Convert.ToInt32(s["cid"]);
            //    Model.firstTime = Convert.ToDateTime(s["firstTime"]);
            //    Model.lastTime = Convert.ToDateTime(s["lastTime"]);
            //    Model.isDrop = Convert.ToBoolean(s["isDrop"]);
            //    object a= s["values"];
            //    Dictionary<string, object> values= a as Dictionary<string, object>;
            //    Model.x_title = values["x.title"].ToString();
            //    Model.x_kind = Convert.ToInt32(values["x.kind"]);
            //    Model.x_type = Convert.ToInt32(values["x.type"]);
            //    Model.x_beginTime = Convert.ToDateTime(values["x.beginTime"]);
            //    Model.x_endTime = Convert.ToDateTime(values["x.beginTime"]);
            //    Model.x_address= values["x.address"].ToString();
            //    Model.x_mode = Convert.ToInt32(values["x.mode"]);
            //    Model.x_isCharge = Convert.ToBoolean(values["x.isCharge"]);
            //    Model.x_chargePrice = Convert.ToSingle(values["x.chargePrice"]);
            //    Model.x_isClose = Convert.ToBoolean(values["x.isClose"]);
            //    Model.x_coverSummary = values["x.coverSummary"].ToString();
            //    Model.x_coverImage = values["x.coverImage"].ToString();
            //    Model.x_readCount = Convert.ToInt32(values["x.readCount"]);
            //    Model.x_praiseCount = Convert.ToInt32(values["x.praiseCount"]);
            //    Model.p_nick = values["p.nick"].ToString();
            //    Model.p_sign = values["p.sign"].ToString();
            //    Model.p_sex = Convert.ToInt32(values["p.sex"]);
            //    Model.p_image = values["p.image"].ToString();
            //}


            // //HttpWebResponse response = HttpCode.CreatePostHttpResponse(url, null, Encoding.UTF8);
            // //Stream stream = response.GetResponseStream();   //获取响应的字符串流
            // //StreamReader sr = new StreamReader(stream); //创建一个stream读取流
            // //string html = sr.ReadToEnd();   //从头读到尾,放到字符串html
            return(View(Model));
        }
Esempio n. 43
0
 public void AddDataInfo(DataInfo coodinates)
 {
     Dirty = true;
     if (this._data == null)
     {
         this._data = new List<DataInfo>();
     }
     this._data.Add(coodinates);
 }
Esempio n. 44
0
        private bool GetEachLineData(ref DataInfo data, string lineString)
        {
            string strTemp;
            string strValue;

            strTemp  = lineString;
            strValue = GetKeyValue(DataInfoKeyStr.X, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.X = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.Y, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.Y = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.Z, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.Z = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.A, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.A = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.B, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.B = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.C, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.C = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.S, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.S = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.T, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.T = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.E1, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.E1 = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.E2, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.E2 = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.E3, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.E3 = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.E4, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.E4 = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.E5, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.E5 = strValue;

            strValue = GetKeyValue(DataInfoKeyStr.E6, strTemp);
            if (strValue == "")
            {
                return(false);
            }
            data.E6 = strValue;

            return(true);
        }
Esempio n. 45
0
    //---------------------------------------------------------------------
    public override Dictionary<int, List<DataInfo>> getTableData(string sqlite_query)
    {
        Dictionary<int, List<DataInfo>> map_table_data = new Dictionary<int, List<DataInfo>>();
        IntPtr stmHandle = Prepare(sqlite_query);
        int columnCount = sqlite3_column_count(stmHandle);
        while (sqlite3_step(stmHandle) == SQLITE_ROW)
        {
            List<DataInfo> list_data = new List<DataInfo>();
            int id = -1;
            for (int i = 0; i < columnCount; i++)
            {
                int data_type = sqlite3_column_type(stmHandle, i);
                string name = Marshal.PtrToStringAnsi(sqlite3_column_name(stmHandle, i));

                DataInfo data_info = new DataInfo();
                data_info.data_type = data_type;
                data_info.data_name = name;
                object data_value = "";
                switch (data_type)
                {
                    case 1:// SQLITE_INTEGER
                        {                            
                            data_value = sqlite3_column_int(stmHandle, i);
                        }
                        break;
                    case 2:// SQLITE_FLOAT
                        {                            
                            data_value = sqlite3_column_double(stmHandle, i);
                        }
                        break;
                    case 3:// SQLITE_TEXT
                        {                            
                            data_value = Marshal.PtrToStringAnsi(sqlite3_column_text(stmHandle, i));
                        }
                        break;
                }                
                data_info.data_value = data_value;
                list_data.Add(data_info);

                if (name.Equals("Id"))
                {
                    id = (int)data_value;
                }
            }
            map_table_data[id] = list_data;
        }
        return map_table_data;
    }
        /// <summary>
        /// the function send request from the server to the history log
        /// </summary>
        public void getHistory()
        {
            DataInfo msg = new DataInfo(CommandEnum.LogCommand, null);

            clientConnection.WriteToServer(msg.toJson());
        }
Esempio n. 47
0
 public virtual void AddAirDataLine(DataInfo dataInfo)
 {
 }
Esempio n. 48
0
        private static async void GetData()
        {
            DataInfo.Add("LunchMenu", new Dictionary <string, string>());
            DataInfo.Add("SchoolSchedule", new Dictionary <string, string>());

            while (true)
            {
                try
                {
                    Logger.LogInformation("<Server> 데이터 가져오기: 시간표를 가져옵니다.");
                    var tmpTimetable = GetTimetable(); // 시간표 가져오기

                    Logger.LogInformation("<Server> 데이터 가져오기: 급식 메뉴를 가져옵니다.");
                    var tmpLunchMenu = GetLunchMenu(); // 급식 메뉴 가져오기

                    Logger.LogInformation("<Server> 데이터 가져오기: 학사 일정을 가져옵니다.");
                    var tmpSchoolSchedule = GetSchoolSchedule(); // 학사 일정 가져오기

                    if (tmpTimetable != null)
                    {
                        // 시간표 데이터 값의 변화가 있는지 확인
                        if (Timetable != null)
                        {
                            if (!JsonCompare(tmpTimetable, Timetable))
                            {
                                Timetable = tmpTimetable;

                                foreach (var className in tmpTimetable.Keys)
                                {
                                    DataInfo["Timetable-" + className].Remove("LastUpdate");
                                    DataInfo["Timetable-" + className].Add("LastUpdate", DateTime.Now.ToString());

                                    DataInfo["Timetable-" + className].Remove("Size");
                                    DataInfo["Timetable-" + className].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpTimetable[className])).ToString());
                                }
                            }
                        }
                        else
                        {
                            Timetable = tmpTimetable;

                            foreach (var className in tmpTimetable.Keys)
                            {
                                DataInfo.Add("Timetable-" + className, new Dictionary <string, string>());

                                DataInfo["Timetable-" + className].Add("LastUpdate", DateTime.Now.ToString());
                                DataInfo["Timetable-" + className].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpTimetable[className])).ToString());
                            }
                        }
                    }

                    if (tmpLunchMenu != null)
                    {
                        // 급식 메뉴 데이터 값의 변화가 있는지 확인
                        if (LunchMenu != null)
                        {
                            if (!JsonCompare(tmpLunchMenu, LunchMenu))
                            {
                                LunchMenu = tmpLunchMenu;

                                DataInfo["LunchMenu"].Remove("LastUpdate");
                                DataInfo["LunchMenu"].Add("LastUpdate", DateTime.Now.ToString());

                                DataInfo["LunchMenu"].Remove("Size");
                                DataInfo["LunchMenu"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpLunchMenu)).ToString());
                            }
                        }
                        else
                        {
                            LunchMenu = tmpLunchMenu;

                            DataInfo["LunchMenu"].Add("LastUpdate", DateTime.Now.ToString());
                            DataInfo["LunchMenu"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpLunchMenu)).ToString());
                        }
                    }

                    if (tmpSchoolSchedule != null)
                    {
                        // 학사 일정 데이터 값의 변화가 있는지 확인
                        if (SchoolSchedule != null)
                        {
                            if (!JsonCompare(tmpSchoolSchedule, SchoolSchedule))
                            {
                                SchoolSchedule = tmpSchoolSchedule;

                                DataInfo["SchoolSchedule"].Remove("LastUpdate");
                                DataInfo["SchoolSchedule"].Add("LastUpdate", DateTime.Now.ToString());

                                DataInfo["SchoolSchedule"].Remove("Size");
                                DataInfo["SchoolSchedule"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpSchoolSchedule)).ToString());
                            }
                        }
                        else
                        {
                            SchoolSchedule = tmpSchoolSchedule;

                            DataInfo["SchoolSchedule"].Add("LastUpdate", DateTime.Now.ToString());
                            DataInfo["SchoolSchedule"].Add("Size", ByteSize.FromBytes(GetJsonByteLength(tmpSchoolSchedule)).ToString());
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError("<Server> 데이터 가져오기: 오류 (" + e.Message + ")");
                    continue;
                }

                await Task.Delay(1800000); // 1000 = 1초, 기본: 30분 (1800000)
            }
        }
Esempio n. 49
0
        public MainWindow()
        {
            InitializeComponent();

            //"127.0.0.1" or "localhost" when you installed Mosquitto Broker in your local machine.
            //"test.mosquitto.org";
            //string BrokerAddress = "192.168.3.5";
            string BrokerAddress = "localhost";
            int    BrokerPort    = 1883;

            // use a unique id as client id, each time we start the application
            clientId = Guid.NewGuid().ToString();

            string username = "******";
            string password = "******";

            // Create a new MQTT client.
            var factory = new MqttFactory();

            mqttClient = factory.CreateMqttClient();

            //// Certificate based authentication
            //List<X509Certificate> certs = new List<X509Certificate>
            //{
            //    new X509Certificate2("certificate1.pfx")
            //};

            // Create TCP based options using the builder.
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(clientId)
                          .WithTcpServer(BrokerAddress, BrokerPort)
                          .WithCredentials(username, password) //("bud", "%spencer%")
                                                               //.WithTls(new MqttClientOptionsBuilderTlsParameters
                                                               //{
                                                               //    UseTls = true,
                                                               //    Certificates = certs,
                                                               //    CertificateValidationHandler = (MqttClientCertificateValidationCallbackContext context) =>
                                                               //    {
                                                               //        // TODO: Check conditions of certificate by using above parameters.
                                                               //        return true;
                                                               //    }
                                                               //})
                                                               //.WithTls()
                          .WithCleanSession()
                          .Build();

            // Subscribing to a topic
            mqttClient.UseConnectedHandler(async e =>
            {
                await UseConnectedMessage();

                //Console.WriteLine("### CONNECTED WITH SERVER ###");

                //// Subscribe to a topic
                //await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build());

                //Console.WriteLine("### SUBSCRIBED ###");
            });

            // Reconnecting
            mqttClient.UseDisconnectedHandler(async e =>
            {
                Dispatcher.Invoke(delegate
                {
                    sbMessage.Text = "Disconnected from MQTT Brokers.";
                });
                //Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(5));

                try
                {
                    await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
                }
                catch
                {
                    //Console.WriteLine("### RECONNECTING FAILED ###");
                }
            });

            mqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    string topic = e.ApplicationMessage.Topic;

                    if (string.IsNullOrWhiteSpace(topic) == false)
                    {
                        string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        ////Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
                        //Dispatcher.Invoke(delegate
                        //{
                        //    // we need this construction because the receiving code in the library and the UI with textbox run on different threads
                        //    txtReceived.Text = payload;
                        //    btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        //});
                        switch (topic.ToLower())
                        {
                        case "picture":
                            BitmapImage bitimg = Utils.ByteToImage(e.ApplicationMessage.Payload);
                            Dispatcher.Invoke(delegate {
                                ImageViewer2.Source   = bitimg;
                                btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            });
                            break;

                        case "bundle":
                            DataInfo imageData = ExtendedSerializerExtensions.Deserialize <DataInfo>(e.ApplicationMessage.Payload);
                            Dispatcher.Invoke(delegate {
                                ImageViewer2.Source   = Utils.ByteToImage(imageData.ImageData);
                                txtReceived.Text      = (string.IsNullOrEmpty(imageData.PublisherMessage) ? "" : imageData.PublisherMessage + "\n") + imageData.FileName;
                                txtReceivedDate.Text  = imageData.SentDateTime.ToString();
                                btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            });
                            break;

                        default:
                            string ReceivedMessage = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                            Dispatcher.Invoke(delegate {
                                txtReceived.Text      = ReceivedMessage;
                                btnSubscribe2.Content = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            });
                            break;
                        }
                    }

                    //string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });

            //mqttClient.ConnectAsync(options, CancellationToken.None).Wait(CancellationToken.None);
            mqttClient.ConnectAsync(options).GetAwaiter().GetResult();
        }
Esempio n. 50
0
    public static void ReadExcelMethod()
    {
        var myWindow = GetWindow <ReadExcel>();

        foreach (var obj in Selection.objects)
        {
            myWindow.excelFile.filePath = AssetDatabase.GetAssetPath(obj);
            myWindow.excelFile.fileName = Path.GetFileName(myWindow.excelFile.filePath);
            myWindow.scriptName         =
                EditorPrefs.GetString(myWindow.excelFile.filePath + myWindow.excelFile.fileName + "ScriptName",
                                      Path.GetFileNameWithoutExtension(myWindow.excelFile.filePath));
            myWindow.isSeparated =
                EditorPrefs.GetBool(myWindow.excelFile.filePath + myWindow.excelFile.fileName + "isSeparated",
                                    false);
            using (var stream = File.Open(myWindow.excelFile.filePath, FileMode.Open, FileAccess.Read))
            {
                //get excl data
                IWorkbook book = null;
                if (Path.GetExtension(myWindow.excelFile.fileName) == ".xls")
                {
                    book = new HSSFWorkbook(stream);
                }
                else
                {
                    book = new XSSFWorkbook(stream);
                }
                //get excl sheet
                for (int j = 0, jMax = book.NumberOfSheets; j < jMax; j++)
                {
                    var sheet     = book.GetSheetAt(j);
                    var sheetInfo = new SheetInfo();
                    sheetInfo.name     = sheet.SheetName;
                    sheetInfo.isEnable =
                        EditorPrefs.GetBool(myWindow.excelFile.filePath + sheetInfo.name + "SheetEnable", true);
                    myWindow.sheetList.Add(sheetInfo);
                    myWindow.scrollVeiwDic.Add(sheetInfo.name, Vector2.zero);
                    // set datatitle list
                    var sheetOne = book.GetSheetAt(j);
                    var title    = sheetOne.GetRow(0); //first row is property
                    if (title == null)
                    {
                        return;
                    }
                    var descRow  = sheetOne.GetRow(1); // second row is describe
                    var dataRow  = sheetOne.GetRow(2); //third row is data begain
                    var dataList = new List <DataInfo>();
                    for (int i = 0, iMax = title.Cells.Count; i < iMax; i++)
                    {
                        if (!string.IsNullOrEmpty(title.Cells[i].ToString()))
                        {
                            var data = new DataInfo();
                            data.titleName = title.Cells[i].ToString();
                            data.desc      = descRow.Cells[i].ToString();
                            data.isArray   = data.titleName.Contains("[]");
                            if (data.isArray)
                            {
                                data.titleName = data.titleName.Replace("[]", "");
                            }
                            data.isEnable = EditorPrefs.GetBool(myWindow.excelFile.filePath + data.titleName + "isEnable",
                                                                true);
                            var cell = dataRow.Cells[i];

                            data = SetDataType(cell, data, myWindow);
                            dataList.Add(data);
                        }
                    }
                    myWindow.dataTitleDic.Add(sheetOne.SheetName, dataList);
                }
            }
        }
    }
Esempio n. 51
0
        public async Task ImportFormAsync(int siteId, string directoryPath, bool overwrite)
        {
            if (!Directory.Exists(directoryPath))
            {
                return;
            }
            var isHistoric = IsHistoric(directoryPath);

            var filePaths = Directory.GetFiles(directoryPath);

            foreach (var filePath in filePaths)
            {
                var feed = AtomFeed.Load(new FileStream(filePath, FileMode.Open));

                var formInfo = new FormInfo();

                foreach (var tableColumn in _formRepository.TableColumns)
                {
                    var value = GetValue(feed.AdditionalElements, tableColumn);
                    formInfo.Set(tableColumn.AttributeName, value);
                }

                formInfo.SiteId = siteId;

                if (isHistoric)
                {
                    formInfo.Title = GetDcElementContent(feed.AdditionalElements, "InputName");
                }

                var srcFormInfo = await _formRepository.GetFormInfoByTitleAsync(siteId, formInfo.Title);

                if (srcFormInfo != null)
                {
                    if (overwrite)
                    {
                        await DeleteAsync(siteId, srcFormInfo.Id);
                    }
                    else
                    {
                        formInfo.Title = await _formRepository.GetImportTitleAsync(siteId, formInfo.Title);
                    }
                }

                formInfo.Id = await _formRepository.InsertAsync(formInfo);

                var directoryName = GetDcElementContent(feed.AdditionalElements, "Id");
                if (isHistoric)
                {
                    directoryName = GetDcElementContent(feed.AdditionalElements, "InputID");
                }
                var titleAttributeNameDict = new NameValueCollection();
                if (!string.IsNullOrEmpty(directoryName))
                {
                    var fieldDirectoryPath = PathUtils.Combine(directoryPath, directoryName);
                    titleAttributeNameDict = await ImportFieldsAsync(siteId, formInfo.Id, fieldDirectoryPath, isHistoric);
                }

                var entryList = new List <AtomEntry>();
                foreach (AtomEntry entry in feed.Entries)
                {
                    entryList.Add(entry);
                }

                entryList.Reverse();

                foreach (var entry in entryList)
                {
                    var dataInfo = new DataInfo();

                    foreach (var tableColumn in _dataRepository.TableColumns)
                    {
                        var value = GetValue(entry.AdditionalElements, tableColumn);
                        dataInfo.Set(tableColumn.AttributeName, value);
                    }

                    var attributes = GetDcElementNameValueCollection(entry.AdditionalElements);
                    foreach (string entryName in attributes.Keys)
                    {
                        dataInfo.Set(entryName, attributes[entryName]);
                    }

                    if (isHistoric)
                    {
                        foreach (var title in titleAttributeNameDict.AllKeys)
                        {
                            dataInfo.Set(title, dataInfo.Get(titleAttributeNameDict[title]));
                        }

                        dataInfo.ReplyContent = GetDcElementContent(entry.AdditionalElements, "Reply");
                        if (!string.IsNullOrEmpty(dataInfo.ReplyContent))
                        {
                            dataInfo.IsReplied = true;
                        }
                        dataInfo.CreatedDate = FormUtils.ToDateTime(GetDcElementContent(entry.AdditionalElements, "adddate"));
                    }

                    await _dataRepository.InsertAsync(formInfo, dataInfo);
                }
            }
        }
Esempio n. 52
0
        public void SendNotify(FormInfo formInfo, List <TableStyle> styles, DataInfo dataInfo)
        {
            //TODO
            //if (formInfo.IsAdministratorSmsNotify &&
            //    !string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyTplId) &&
            //    !string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyMobile))
            //{
            //    var smsPlugin = Context.PluginApi.GetPlugin<SMS.Plugin>();
            //    if (smsPlugin != null && smsPlugin.IsReady)
            //    {
            //        var parameters = new Dictionary<string, string>();
            //        if (!string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyKeys))
            //        {
            //            var keys = formInfo.AdministratorSmsNotifyKeys.Split(',');
            //            foreach (var key in keys)
            //            {
            //                if (FormUtils.EqualsIgnoreCase(key, nameof(DataInfo.Id)))
            //                {
            //                    parameters.Add(key, dataInfo.Id.ToString());
            //                }
            //                else if (FormUtils.EqualsIgnoreCase(key, nameof(DataInfo.AddDate)))
            //                {
            //                    if (dataInfo.AddDate.HasValue)
            //                    {
            //                        parameters.Add(key, dataInfo.AddDate.Value.ToString("yyyy-MM-dd HH:mm"));
            //                    }
            //                }
            //                else
            //                {
            //                    var value = string.Empty;
            //                    var style =
            //                        styleList.FirstOrDefault(x => FormUtils.EqualsIgnoreCase(key, x.Title));
            //                    if (style != null)
            //                    {
            //                        value = LogManager.GetValue(style, dataInfo);
            //                    }

            //                    parameters.Add(key, value);
            //                }
            //            }
            //        }

            //        smsPlugin.Send(formInfo.AdministratorSmsNotifyMobile,
            //            formInfo.AdministratorSmsNotifyTplId, parameters, out _);
            //    }
            //}

            //if (formInfo.IsAdministratorMailNotify &&
            //    !string.IsNullOrEmpty(formInfo.AdministratorMailNotifyAddress))
            //{
            //    var mailPlugin = Context.PluginApi.GetPlugin<Mail.Plugin>();
            //    if (mailPlugin != null && mailPlugin.IsReady)
            //    {
            //        var templateHtml = MailTemplateManager.GetTemplateHtml();
            //        var listHtml = MailTemplateManager.GetListHtml();

            //        var keyValueList = new List<KeyValuePair<string, string>>
            //        {
            //            new KeyValuePair<string, string>("编号", dataInfo.Guid)
            //        };
            //        if (dataInfo.AddDate.HasValue)
            //        {
            //            keyValueList.Add(new KeyValuePair<string, string>("提交时间", dataInfo.AddDate.Value.ToString("yyyy-MM-dd HH:mm")));
            //        }
            //        foreach (var style in styleList)
            //        {
            //            keyValueList.Add(new KeyValuePair<string, string>(style.Title,
            //                LogManager.GetValue(style, dataInfo)));
            //        }

            //        var list = new StringBuilder();
            //        foreach (var kv in keyValueList)
            //        {
            //            list.Append(listHtml.Replace("{{key}}", kv.Key).Replace("{{value}}", kv.Value));
            //        }

            //        var siteInfo = Context.SiteApi.GetSiteInfo(formInfo.SiteId);

            //        mailPlugin.Send(formInfo.AdministratorMailNotifyAddress, string.Empty,
            //            "[SiteServer CMS] 通知邮件",
            //            templateHtml.Replace("{{title}}", $"{formInfo.Title} - {siteInfo.SiteName}").Replace("{{list}}", list.ToString()), out _);
            //    }
            //}

            //if (formInfo.IsUserSmsNotify &&
            //    !string.IsNullOrEmpty(formInfo.UserSmsNotifyTplId) &&
            //    !string.IsNullOrEmpty(formInfo.UserSmsNotifyMobileName))
            //{
            //    var smsPlugin = Context.PluginApi.GetPlugin<SMS.Plugin>();
            //    if (smsPlugin != null && smsPlugin.IsReady)
            //    {
            //        var parameters = new Dictionary<string, string>();
            //        if (!string.IsNullOrEmpty(formInfo.UserSmsNotifyKeys))
            //        {
            //            var keys = formInfo.UserSmsNotifyKeys.Split(',');
            //            foreach (var key in keys)
            //            {
            //                if (FormUtils.EqualsIgnoreCase(key, nameof(DataInfo.Id)))
            //                {
            //                    parameters.Add(key, dataInfo.Id.ToString());
            //                }
            //                else if (FormUtils.EqualsIgnoreCase(key, nameof(DataInfo.AddDate)))
            //                {
            //                    if (dataInfo.AddDate.HasValue)
            //                    {
            //                        parameters.Add(key, dataInfo.AddDate.Value.ToString("yyyy-MM-dd HH:mm"));
            //                    }
            //                }
            //                else
            //                {
            //                    var value = string.Empty;
            //                    var style =
            //                        styleList.FirstOrDefault(x => FormUtils.EqualsIgnoreCase(key, x.Title));
            //                    if (style != null)
            //                    {
            //                        value = LogManager.GetValue(style, dataInfo);
            //                    }

            //                    parameters.Add(key, value);
            //                }
            //            }
            //        }

            //        var mobileFieldInfo = styleList.FirstOrDefault(x => FormUtils.EqualsIgnoreCase(formInfo.UserSmsNotifyMobileName, x.Title));
            //        if (mobileFieldInfo != null)
            //        {
            //            var mobile = LogManager.GetValue(mobileFieldInfo, dataInfo);
            //            if (!string.IsNullOrEmpty(mobile))
            //            {
            //                smsPlugin.Send(mobile, formInfo.UserSmsNotifyTplId, parameters, out _);
            //            }
            //        }
            //    }
            //}
        }
Esempio n. 53
0
    //---------------------------------------------------------------------
    public override Dictionary<int, List<DataInfo>> getTableData(string sqlite_query)
    {
        SQLiteQuery qr = new SQLiteQuery(mSQLiteDB, sqlite_query);
        Dictionary<int, List<DataInfo>> map_table_data = new Dictionary<int, List<DataInfo>>();

        while (qr.Step())
        {
            string[] data_names = qr.Names;
            List<DataInfo> list_data = new List<DataInfo>();
            int id = -1;
            foreach (var i in data_names)
            {
                bool is_null = qr.IsNULL(i);
                if (is_null)
                {
                    continue;
                }

                int field_type = qr.GetFieldType(i);
                DataInfo data_info = new DataInfo();
                data_info.data_type = field_type;
                data_info.data_name = i;
                object data_value = "";
                switch (field_type)
                {
                    case 1:// SQLITE_INTEGER
                        {
                            data_value = qr.GetInteger(i);
                        }
                        break;
                    case 2:// SQLITE_FLOAT
                        {
                            data_value = qr.GetDouble(i);
                        }
                        break;
                    case 3:// SQLITE_TEXT
                        {
                            data_value = qr.GetString(i);
                        }
                        break;
                }
                data_info.data_value = data_value;
                list_data.Add(data_info);
                if (i.Equals("Id"))
                {
                    id = (int)data_value;
                }
            }

            map_table_data[id] = list_data;
        }

        return map_table_data;
    }
Esempio n. 54
0
        public IHttpActionResult DeleteDataInfo(DataInfo dataInfo)
        {
            var ret = _knowledgeService.DeleteDataInfo(dataInfo, WorkUser);

            return(Ok(ret));
        }
Esempio n. 55
0
        public async Task <DataInfo> GetDataInfoAsync(int dataId, int formId, List <TableStyle> styles)
        {
            DataInfo dataInfo;

            if (dataId > 0)
            {
                dataInfo = await _dataRepository.GetDataInfoAsync(dataId);
            }
            else
            {
                dataInfo = new DataInfo
                {
                    FormId = formId
                };

                foreach (var style in styles)
                {
                    if (style.InputType == InputType.Text || style.InputType == InputType.TextArea || style.InputType == InputType.TextEditor || style.InputType == InputType.Hidden)
                    {
                        if (string.IsNullOrEmpty(style.DefaultValue))
                        {
                            continue;
                        }

                        dataInfo.Set(style.AttributeName, style.DefaultValue);
                    }
                    else if (style.InputType == InputType.Number)
                    {
                        if (string.IsNullOrEmpty(style.DefaultValue))
                        {
                            continue;
                        }

                        dataInfo.Set(style.AttributeName, TranslateUtils.ToInt(style.DefaultValue));
                    }
                    else if (style.InputType == InputType.CheckBox || style.InputType == InputType.SelectMultiple)
                    {
                        var value = new List <string>();

                        if (style.Items != null)
                        {
                            foreach (var item in style.Items)
                            {
                                if (item.Selected)
                                {
                                    value.Add(item.Value);
                                }
                            }
                        }

                        dataInfo.Set(style.AttributeName, value);
                    }
                    else if (style.InputType == InputType.Radio || style.InputType == InputType.SelectOne)
                    {
                        if (style.Items != null)
                        {
                            foreach (var item in style.Items)
                            {
                                if (item.Selected)
                                {
                                    dataInfo.Set(style.AttributeName, item.Value);
                                }
                            }
                        }
                        else if (!string.IsNullOrEmpty(style.DefaultValue))
                        {
                            dataInfo.Set(style.AttributeName, style.DefaultValue);
                        }
                    }
                }
            }

            return(dataInfo);
        }
Esempio n. 56
0
        public void Load(System.IO.Stream stream)
        {
            fileSize = stream.Length;
            using (var reader = new FileReader(stream))
            {
                pmdlCount = 0;
                ptexCount = 0;
                ptexList.Clear();
                ddsList.Clear();
                // Read header for data locations
                files.Clear();
                reader.Position  = 4;
                reader.ByteOrder = byteOrder;
                if (reader.ReadUInt32() != 2001)
                {
                    byteOrder = ByteOrder.BigEndian;
                }
                reader.ByteOrder            = byteOrder;
                reader.Position             = 0;
                header.version              = reader.ReadUInt32(4);
                reader.Position            += 4;
                header.flag1                = reader.ReadUInt16();
                header.flag2                = reader.ReadUInt16();
                header.dataInfoCount        = reader.ReadUInt32();
                header.dataInfoSize         = reader.ReadUInt32();
                header.tagCount             = reader.ReadUInt32();
                header.tagSize              = reader.ReadUInt32();
                header.relocationDataOffset = reader.ReadUInt32();
                header.relocationDataSize   = reader.ReadInt32();
                reader.Position            += 92;
                // Create arrays for multiple data and tag info objects
                DataInfo[] dataInfos = new DataInfo[header.dataInfoCount];
                TagInfo[]  tagInfos  = new TagInfo[header.tagCount];

                for (int i = 0; i < header.dataInfoCount; i++)
                {
                    // Create and assign properties to a new DataInfo until the count specified in the header is reached
                    dataInfos[i] = new DataInfo()
                    {
                        unknown1   = reader.ReadUInt32(),
                        textOffset = reader.ReadUInt32(),
                        unknown2   = reader.ReadUInt32(),
                        unknown3   = reader.ReadUInt32(),
                        dataSize   = reader.ReadInt32(),
                        dataSize2  = reader.ReadUInt32(),
                        dataOffset = reader.ReadInt32(),
                        unknown4   = reader.ReadUInt32(),
                        zero1      = reader.ReadUInt32(),
                        zero2      = reader.ReadUInt32(),
                        zero3      = reader.ReadUInt32(),
                        zero4      = reader.ReadUInt32()
                    };
                }
                saveData = dataInfos;

                for (int i = 0; i < header.tagCount; i++)
                {
                    // Get tags for file extensions, data, and names
                    tagInfos[i] = new TagInfo()
                    {
                        magic      = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(4)),
                        dataOffset = reader.ReadInt32(),
                        flag       = reader.ReadUInt32(),
                        textOffset = reader.ReadInt32(),
                        name       = "default"
                    };
                }


                // Get extra data, currently unused except for saving the file
                if (header.dataInfoCount > 2)
                {
                    reader.Position = dataInfos[2].dataOffset;
                    extraData       = reader.ReadBytes(dataInfos[2].dataSize);
                }

                // Get relocation data and write to byte array
                reader.Position = header.relocationDataOffset;
                relocationData  = reader.ReadBytes(header.relocationDataSize);

                // Compile filenames and add as files
                for (long i = 0; i < header.tagCount - 1; i++)
                {
                    reader.Position = dataInfos[0].dataOffset + tagInfos[i].textOffset;
                    string filename = reader.ReadZeroTerminatedString();
                    tagInfos[i].name = filename;
                    saveTag          = tagInfos;
                    if (!tagInfos[i].magic.StartsWith("\0"))
                    {
                        filename = filename + "." + tagInfos[i].magic.ToLower();
                    }
                    reader.Position = dataInfos[1].dataOffset + tagInfos[i].dataOffset;
                    FileEntry file = new FileEntry()
                    {
                        FileName = filename,
                        FileData = reader.ReadBytes(tagInfos[i + 1].dataOffset - tagInfos[i].dataOffset)
                    };
                    reader.Position = dataInfos[1].dataOffset + tagInfos[i].dataOffset;

                    // Load textures as a dds using the PTEX pointer
                    if (tagInfos[i].magic == "PTEX")
                    {
                        reader.Position += 88;
                        Ptex ptex = new Ptex()
                        {
                            ptexOffset = reader.Position,
                            width      = reader.ReadUInt32(),
                            height     = reader.ReadUInt32(),
                            unknown    = reader.ReadUInt32(),
                            ddsOffset  = reader.ReadUInt32(),
                            ddsSize    = reader.ReadInt32()
                        };
                        reader.Position  = dataInfos[header.dataInfoCount - 1].dataOffset;
                        reader.Position += ptex.ddsOffset;
                        DDS dds = new DDS(reader.ReadBytes(ptex.ddsSize))
                        {
                            WiiUSwizzle = false,
                            FileType    = FileType.Image,
                            Text        = filename + ".dds",
                            FileName    = filename,
                            CanReplace  = true
                        };
                        reader.Position  = dataInfos[header.dataInfoCount - 1].dataOffset;
                        reader.Position += ptex.ddsOffset;
                        ptexList.Add(ptex);
                        Nodes.Add(dds);
                        ddsList.Add(dds);
                        FileType = FileType.Image;
                        ptexCount++;
                    }

                    if (tagInfos[i].magic == "PMDL")
                    {
                        reader.Position += 8;
                        Pmdl pmdl = new Pmdl()
                        {
                            relocationDataCount = reader.ReadInt16(),
                            pmdlSize            = reader.ReadInt16()
                        };
                        reader.Position             += 4;
                        pmdl.modelTextOffset         = reader.ReadInt32();
                        reader.Position             += 36;
                        pmdl.sumVertCount            = reader.ReadInt32();
                        pmdl.faceStartOffsetRelative = reader.ReadInt32();
                        pmdl.vertexStartOffset       = reader.ReadInt32();
                        reader.Position             += 4;
                        pmdl.sumFaceCount            = reader.ReadInt32();
                        pmdl.faceStartOffset         = reader.ReadInt32();
                        reader.Position             += 48;
                        pmdl.subInfoCount            = reader.ReadInt32();
                        pmdl.offsetToSubInfosStart   = reader.ReadInt32();
                        pmdl.endOfSubInfos           = reader.ReadInt32();
                        reader.Position              = pmdl.offsetToSubInfosStart + dataInfos[1].dataOffset;
                        int[] subInfoStarts = new int[pmdl.subInfoCount];
                        subInfoStarts = reader.ReadInt32s(pmdl.subInfoCount);
                        SubInfoData[] subInfoDatas = new SubInfoData[pmdl.subInfoCount];
                        for (int t = 0; t < pmdl.subInfoCount; t++)
                        {
                            reader.Position = subInfoStarts[t] + dataInfos[1].dataOffset;
                            SubInfoData subInfoData = new SubInfoData()
                            {
                                unknown1             = reader.ReadInt32(),
                                unknown2             = reader.ReadInt32(),
                                unknown3             = reader.ReadInt32(),
                                unknown4             = reader.ReadInt32(),
                                unknown5             = reader.ReadInt32(),
                                unknown6             = reader.ReadInt32(),
                                vertexCount          = reader.ReadInt32(),
                                unknown8             = reader.ReadInt32(),
                                previousFaceCount    = reader.ReadInt32(),
                                faceCount            = reader.ReadInt32(),
                                unknown11            = reader.ReadInt32(),
                                unknown12            = reader.ReadInt32(),
                                vertexOffsetRelative = reader.ReadInt32(),
                                normalUVOffset       = reader.ReadInt32(),
                                faceOffset           = reader.ReadInt32(),
                                sameSizeorOffset     = reader.ReadInt32(),
                                sameSizeorOffset2    = reader.ReadInt32(),
                                sameSizeorOffset3    = reader.ReadInt32(),
                                sameSizeorOffset4    = reader.ReadInt32(),
                                sameSizeorOffset5    = reader.ReadInt32()
                            };

                            pmdl.verticesCount = subInfoData.vertexCount;
                            pmdl.facesCount    = subInfoData.faceCount;
                            subInfoDatas[t]    = subInfoData;
                        }
                        var renderedMesh = new GenericRenderedObject();
                        var renderer     = new GenericModelRenderer();
                        renderedMesh.ImageKey         = "mesh";
                        renderedMesh.SelectedImageKey = "mesh";
                        renderedMesh.Checked          = true;
                        int[] normalUVSize = new int[pmdl.subInfoCount];
                        if (pmdl.subInfoCount > 1)
                        {
                            int remember = 0;
                            for (int a = 0; a + 1 < pmdl.subInfoCount; a++)
                            {
                                pmdl.normalUVStart = subInfoDatas[a].normalUVOffset;
                                pmdl.normalUVEnd   = subInfoDatas[a + 1].normalUVOffset;
                                normalUVSize[a]    = (int)(pmdl.normalUVEnd - pmdl.normalUVStart);
                                remember           = a;
                            }
                            pmdl.normalUVStart = subInfoDatas[remember + 1].normalUVOffset;
                            pmdl.normalUVEnd   = subInfoDatas[remember + 1].normalUVOffset;
                        }
                        else if (pmdl.subInfoCount >= 1)
                        {
                            for (int x = 0; x < pmdl.subInfoCount; x++)
                            {
                                int stride = (int)(normalUVSize[x] / subInfoDatas[x].vertexCount);
                                reader.Position = pmdl.vertexStartOffset + subInfoDatas[x].vertexOffsetRelative;
                                for (int j = 0; j < subInfoDatas[x].vertexCount; j++)
                                {
                                    Vertex vert = new Vertex();
                                    vert.pos = new OpenTK.Vector3(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32());
                                }
                            }
                        }
                    }
                    files.Add(file);
                }

                // For the last file, read until the end of the raw data section
                TagInfo lastTag = tagInfos[header.tagCount - 1];
                reader.Position = dataInfos[0].dataOffset + lastTag.textOffset;
                string filename2 = reader.ReadZeroTerminatedString();
                tagInfos[header.tagCount - 1].name = filename2;
                saveTag = tagInfos;
                if (!lastTag.magic.StartsWith("\0"))
                {
                    filename2 = filename2 + "." + lastTag.magic.ToLower();
                }
                reader.Position = dataInfos[1].dataOffset + lastTag.dataOffset;
                FileEntry file2 = new FileEntry()
                {
                    FileName = filename2,
                    FileData = reader.ReadBytes(dataInfos[1].dataSize - lastTag.dataOffset)
                };
                if (tagInfos[header.tagCount - 1].magic == "PTEX")
                {
                    reader.Position = dataInfos[1].dataOffset + tagInfos[header.tagCount - 1].dataOffset + 88;
                    Ptex ptex = new Ptex()
                    {
                        ptexOffset = reader.Position,
                        width      = reader.ReadUInt32(),
                        height     = reader.ReadUInt32(),
                        unknown    = reader.ReadUInt32(),
                        ddsOffset  = reader.ReadUInt32(),
                        ddsSize    = reader.ReadInt32()
                    };
                    reader.Position  = dataInfos[header.dataInfoCount - 1].dataOffset;
                    reader.Position += ptex.ddsOffset;
                    DDS dds = new DDS(reader.ReadBytes(ptex.ddsSize))
                    {
                        WiiUSwizzle = false,
                        FileType    = FileType.Image,
                        Text        = filename2 + ".dds",
                        FileName    = filename2,
                        CanReplace  = true,
                    };
                    reader.Position  = dataInfos[header.dataInfoCount - 1].dataOffset;
                    reader.Position += ptex.ddsOffset;
                    ptexList.Add(ptex);
                    Nodes.Add(dds);
                    ddsList.Add(dds);
                    FileType = FileType.Image;
                    ptexCount++;
                }
                if (tagInfos[0].magic == "enti")
                {
                    reader.Position = dataInfos[1].dataOffset + tagInfos[0].dataOffset;
                    var position     = reader.Position;
                    var entityHeader = new Entity.EntityHeader()
                    {
                        entitiesOffset = reader.ReadUInt32(),
                        entitiesCount  = reader.ReadUInt32(),
                        unknown1       = reader.ReadUInt32(),
                        unknown2       = reader.ReadUInt32()
                    };
                    reader.Position = position + entityHeader.entitiesOffset;
                    var properties = new Entity.Property[entityHeader.entitiesCount];
                    //var entities = new Entity.Entity[entityHeader.entitiesCount];
                    //for (int i = 0; i < entityHeader.entitiesCount; i++)
                    //{
                    //    entities[i].entityNameOffset = reader.ReadUInt32();
                    //    entities[i].propertiesCount = reader.ReadUInt16();
                    //    entities[i].propertiesCount2 = reader.ReadUInt16();
                    //    entities[i].propertiesOffset = reader.ReadUInt32();
                    //    entities[i].matrixOffset = reader.ReadUInt32();
                    //    entities[i].positionOffset = reader.ReadUInt32();
                    //    entities[i].unknown = reader.ReadUInt32();
                    //    entities[i].flag = reader.ReadUInt32();
                    //    entities[i].valuesOffset = reader.ReadUInt32();
                    //}

                    var entities = new Entity.Entity[entityHeader.entitiesCount];


                    for (int i = 0; i < entityHeader.entitiesCount; i++)
                    {
                        reader.Position = position + entities[i].propertiesOffset;
                    }
                }

                files.Add(file2);
            }
        }