protected override void setMessageData(int pIndex, string pText, Color pColor) { messagesData[pIndex] = new TextData() { timestamp = Time.realtimeSinceStartup, color = pColor, text = pText, }; }
public void SaveAndRead() { string fileName = Path.GetTempFileName(); var data = new TextData() { Items = new List<string> {"Hello", "World"}, Name = "Test" }; _storageService.Set(fileName, data); var data2 = _storageService.Get<TextData>(fileName); Assert.AreEqual(data.Name, data2.Name); Assert.AreEqual(data.Items.Count, data2.Items.Count); }
public TextBuffer(TextData data) { this.TextData = data; this.LastChange = new TextChange { OldTextData = TextData.Empty, NewTextData = data, Replacement = data }; this.Formatter = new TextFormatter(this); this.pencilEvent = new AutoResetEvent(true); // Signalled -- pencil is available this.activePencil = null; this.undoStack = new Stack<TextUndoUnit>(); this.redoStack = new Stack<TextUndoUnit>(); this.undoObservers = new List<ITextUndoObserver>(); }
private IDocument <TextData> GetTextDoc(TextInfo text, int chapter) { return(_conn.Get <TextData>(TextData.GetTextDocId(_projectDoc.Id, text.BookNum, chapter))); }
// Start is called before the first frame update void Start() { // baseLoc = 5.5f; body = GameObject.Find("bodyEric"); // animator = body.GetComponent<Animator>(); // animator.SetIKPosition(AvatarIKGoal.LeftFoot, new Vector3(0.1f,0.1f,0.1f)); init_box = GameObject.Find("init_box"); Rigidbody rb = init_box.AddComponent <Rigidbody>(); rb.useGravity = false; rb.mass = 0; init_box.AddComponent <TTriggerEvent>(); // cube = GameObject.Find("Cube-glow"); coroutine = CreateCube(); StartCoroutine(coroutine); variables = new Variables("test"); string lng = Application.systemLanguage.ToString(); // ps.Stop; // ps.main.startDelay = 5.0f; // if (TextData.isLanguge(lng)){userLang = lng;} // userLang = "Spanish"; listPoses["leftHandForvard"] = new PoseData() { id = "leftHandForvard" , tex = Resources.Load <Texture2D>("hand_left") , message = TextData.getMessage(userLang, "leftHandForvard") , boxDataPos = new Vector3(1.13f, 2.87f, 3.25f) }; listPoses["rightHandForvard"] = new PoseData() { id = "rightHandForvard" , tex = Resources.Load <Texture2D>("hand_right") , message = TextData.getMessage(userLang, "rightHandForvard") , boxDataPos = new Vector3(0.51f, 2.87f, 3.25f) }; // ,["rightHandForvard"]=, // ,["leftHandUp"]=, // ,["rightHandUp"]=, // ,["leftHandDown"]=, // ,["rightHandDown"]= List <string> keyList = new List <string>(bodyParts.Keys); GameObject camTimedPointer = GameObject.Find("GvrReticlePointer"); timedPointer = camTimedPointer.GetComponent <Renderer>().material; // foreach(string key in keyList){ bodyParts[key] = FindChild(body.transform,key);} // if(bodyParts["upperarm_l"]!= null){ // bodyParts["upperarm_l"].Rotate(0, 0, 90, Space.Self); // bodyParts["upperarm_r"].Rotate(0, 0, 90, Space.Self); // } // Debug.Log(body.transform.RightHand); animator = body.GetComponent <Animator>(); // Transform arm = animator.GetBoneTransform(HumanBodyBones.LeftUpperArm); // Debug.Log(arm); // arm.LookAt(init_box.transform.position); // Vector3 Offset = new Vector3(0,90,90); // arm.rotation = arm.rotation * Quaternion.Euler(Offset); // obj.Rotate(0,0,90); // Quaternion handRotation = Quaternion.LookRotation(objToAimAt.position - new Vector3(0,0,90)); // animator.SetIKRotationWeight(animator.AvatarIKGoal.RightHand, 1.0f); // animator.SetIKRotation(animator.AvatarIKGoal.RightHand, handRotation); StartCoroutine(animationBodyPart(animator.GetBoneTransform(HumanBodyBones.LeftUpperArm), new Vector3(0, 0, 90))); // Transform characterHips = animator.GetBoneTransform(HumanBodyBones.Hips); Debug.Log(baseLoc); // doKnuckle(bodyParts["hand_l"]); // doKnuckle(bodyParts["hand_r"]); // GameObject msgObj2 = Utility.ShowMessage("selAllCol", "", TextData.getMessage(userLang, "btnStart"), new Vector2(1200, 200), TextAlignmentOptions.Midline, new Vector2(0, 20), this); con = new Connection(); // initPose(); // drawLines(); }
protected override void Seed(DatabaseContext context) { //adding admin user EverNoteUser admin = new EverNoteUser() { Name = "Yasin", SurName = "Akdoğan", Email = "*****@*****.**", ActivateGuid = Guid.NewGuid(), IsActive = true, IsAdmin = true, UserName = "******", Password = "******", CreatedOn = DateTime.Now, ModifiedOn = DateTime.Now.AddMinutes(5), ModifiedUserName = "******", ProfilImageFileName = "userimg.jfif" }; //adding standart user EverNoteUser standartUser = new EverNoteUser() { Name = "Ahmet", SurName = "Korkmaz", Email = "*****@*****.**", ActivateGuid = Guid.NewGuid(), IsActive = true, IsAdmin = true, UserName = "******", Password = "******", CreatedOn = DateTime.Now, ModifiedOn = DateTime.Now.AddMinutes(5), ModifiedUserName = "******", ProfilImageFileName = "userimg.jfif" }; context.EverNoteUsers.Add(admin); context.EverNoteUsers.Add(standartUser); //adding fake user for (int i = 0; i < 8; i++) { EverNoteUser fakeUser = new EverNoteUser() { Name = NameData.GetFirstName(), SurName = NameData.GetSurname(), Email = NetworkData.GetEmail(), ActivateGuid = Guid.NewGuid(), IsActive = true, IsAdmin = true, UserName = $"user{i}", Password = "******", CreatedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedUserName = $"user{i}", ProfilImageFileName = "userimg.jfif" }; context.EverNoteUsers.Add(fakeUser); } context.SaveChanges(); //User List For Using List <EverNoteUser> userList = context.EverNoteUsers.ToList(); //adding fake Categories for (int i = 0; i < 10; i++) { Category cat = new Category() { Title = PlaceData.GetStreetName(), Description = PlaceData.GetAddress(), CreatedOn = DateTime.Now, ModifiedOn = DateTime.Now, ModifiedUserName = "******" }; context.Categories.Add(cat); //adding fake notes for (int k = 0; k < NumberData.GetNumber(5, 9); k++) { EverNoteUser owner = userList[NumberData.GetNumber(0, userList.Count - 1)]; Note note = new Note() { Title = TextData.GetAlphabetical(NumberData.GetNumber(5, 25)), Text = TextData.GetSentences(NumberData.GetNumber(1, 3)), Category = cat, IsDraft = false, LikeCount = NumberData.GetNumber(1, 9), Owner = owner, CreatedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedUserName = owner.UserName }; cat.Notes.Add(note); //adding fake comment for (int j = 0; j < NumberData.GetNumber(3, 5); j++) { EverNoteUser comment_owner = userList[NumberData.GetNumber(0, userList.Count - 1)]; Comment comment = new Comment() { Text = TextData.GetSentence(), Owner = comment_owner, CreatedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedUserName = comment_owner.UserName, //Note=note }; note.Comments.Add(comment); //adding fake Likes for (int m = 0; m < note.LikeCount; m++) { Liked liked = new Liked() { LikedUser = userList[m] }; note.Likes.Add(liked); } } } context.SaveChanges(); } }
protected override void Seed(DatabaseContext context) { //admin kullanıcı ekleme işlemi. EverNoteUser admin = new EverNoteUser() { Name = "Aydan", SurName = "Torun", Email = "*****@*****.**", ActivateGuid = Guid.NewGuid(), IsActive = true, IsAdmin = true, UserName = "******", Password = "******", CreatedOn = DateTime.Now, ModifiedOn = DateTime.Now.AddMinutes(5), ModifiedUserName = "******", ProfilImageFileName = "user.png" }; //standart kullanıcı ekleme. EverNoteUser standartUser = new EverNoteUser() { Name = "Maykıl", SurName = "Ceksın", Email = "ceksı[email protected]", ActivateGuid = Guid.NewGuid(), IsActive = true, IsAdmin = false, UserName = "******", Password = "******", CreatedOn = DateTime.Now, ModifiedOn = DateTime.Now.AddMinutes(5), ModifiedUserName = "******", ProfilImageFileName = "user.png" }; context.EverNoteUsers.Add(admin); context.EverNoteUsers.Add(standartUser); //fake kullanıcı ekleme. for (int i = 0; i < 8; i++) { EverNoteUser fakeuser = new EverNoteUser() { Name = NameData.GetFirstName(), SurName = NameData.GetSurname(), Email = NetworkData.GetEmail(), ActivateGuid = Guid.NewGuid(), IsActive = true, IsAdmin = false, UserName = $"user{i}", Password = "******", CreatedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedUserName = $"user{i}", ProfilImageFileName = "user.png" }; context.EverNoteUsers.Add(fakeuser); } context.SaveChanges(); //User List For using List <EverNoteUser> userList = context.EverNoteUsers.ToList(); //Adding fake Categories for (int i = 0; i < 10; i++) { Category cat = new Category() { Title = PlaceData.GetStreetName(), Description = PlaceData.GetAddress(), CreatedOn = DateTime.Now, ModifiedOn = DateTime.Now, ModifiedUserName = "******" }; context.Categories.Add(cat); //Adding fake Notes for (int k = 0; k < NumberData.GetNumber(5, 9); k++) { EverNoteUser owner = userList[NumberData.GetNumber(0, userList.Count - 1)]; Note note = new Note() { Title = TextData.GetAlphabetical(NumberData.GetNumber(5, 25)), Text = TextData.GetSentences(NumberData.GetNumber(1, 3)), Category = cat, IsDraft = false, LikeCount = NumberData.GetNumber(1, 9), Owner = owner, CreatedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedUserName = owner.UserName }; cat.Notes.Add(note); //Adding fake comments for (int j = 0; j < NumberData.GetNumber(3, 5); j++) { EverNoteUser comment_owner = userList[NumberData.GetNumber(0, userList.Count - 1)]; Comment comment = new Comment() { Text = TextData.GetSentence(), Owner = comment_owner, CreatedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedOn = DateTimeData.GetDatetime(DateTime.Now.AddYears(-2), DateTime.Now), ModifiedUserName = comment_owner.UserName, // Note=note }; note.Comments.Add(comment); //Adding sahte beğeniler for (int m = 0; m < note.LikeCount; m++) { Liked liked = new Liked() { LikedUser = userList[m] }; note.Likes.Add(liked); } } } context.SaveChanges(); } }
public static void UpdateTextLagunage() { TextData.Initialize(); }
private static string Arg(TextData argHash, char key, string _default) { return(argHash.ContainsKey(key.ToString()) ? argHash[key.ToString()] : _default); }
/// <summary> /// Add text at 2D position. /// </summary> /// <param name="pos">XY screen coordinates (pixels)</param> /// <param name="text">Text to draw</param> /// <param name="color">Color of text</param> public void AddText(Vector2 pos, String text, Justify justify, Color color) { if (sTextList.Count >= MAX_TEXT_LINES) { return; } TextData textData = new TextData(); textData.mPos.X = pos.X; textData.mPos.Y = pos.Y; textData.mPos.Z = 0.0f; textData.mText = text; textData.mColor = color; textData.mJustify = justify; textData.mIsTransformed = true; sTextList.Add(textData); }
public Get() { data = new TextData(); }
public static string[] RemoveWords(string text) { var mlContext = new MLContext(); var emptySamples = new List <TextData>(); var emptyDataView = mlContext.Data.LoadFromEnumerable(emptySamples); var textPipeline = mlContext.Transforms.Text.TokenizeIntoWords("Words", "Text") .Append(mlContext.Transforms.Text.RemoveStopWords( "WordsWithoutStopWords", "Words", stopwords: new[] { "a", "about", "above", "above", "across", "after", "afterwards", "again", "against", "all", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "amoungst", "amount", "an", "and", "another", "any", "anyhow", "anyone", "anything", "anyway", "anywhere", "are", "around", "as", "at", "back", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "bill", "both", "bottom", "but", "by", "call", "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de", "describe", "detail", "do", "done", "down", "due", "during", "each", "eg", "eight", "either", "eleven", "else", "elsewhere", "empty", "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few", "fifteen", "fify", "fill", "find", "fire", "first", "five", "for", "former", "formerly", "forty", "found", "four", "from", "front", "full", "further", "get", "give", "go", "had", "has", "hasnt", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "hundred", "ie", "if", "in", "inc", "indeed", "interest", "into", "is", "it", "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd", "made", "many", "may", "me", "meanwhile", "might", "mill", "mine", "more", "moreover", "most", "mostly", "move", "much", "must", "my", "myself", "name", "namely", "neither", "never", "nevertheless", "next", "nine", "no", "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves", "out", "over", "own", "part", "per", "perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed", "seeming", "seems", "serious", "several", "she", "should", "show", "side", "since", "sincere", "six", "sixty", "so", "some", "somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "system", "take", "ten", "than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "thereupon", "these", "they", "thick", "thin", "third", "this", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", "twelve", "twenty", "two", "un", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what", "whatever", "when", "whence", "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "whoever", "whole", "whom", "whose", "why", "will", "with", "within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves", "the", "s", "seven", "zero", "i", })); var textTransformer = textPipeline.Fit(emptyDataView); var predictionEngine = mlContext.Model.CreatePredictionEngine <TextData, TransformedTextData>(textTransformer); Stemmer s = new Stemmer(); string[] tokenized_text = Tokenizer.Tokenize(text); int t_l = tokenized_text.Length; for (int i = 0; i < t_l; i++) { tokenized_text[i] = s.stem(tokenized_text[i]); } text = string.Join(" ", tokenized_text); // Call the prediction API to remove stop words. var data = new TextData() { Text = text }; var prediction = predictionEngine.Predict(data); // Print the length of the word vector after the stop words removed. Console.WriteLine("Number of words: " + prediction.WordsWithoutStopWords .Length); //System.IO.File.WriteAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "text.txt"), string.Join(" ", prediction.WordsWithoutStopWords)); // Print the word vector without stop words. //Console.WriteLine("\nWords without stop words: " + string.Join(",", // prediction.WordsWithoutStopWords)); // Expected output: // Number of words: 14 // Words without stop words: ML.NET's,RemoveStopWords,API,removes,stop,words,text/string,using,list,of,stop,words,provided,user. return(prediction.WordsWithoutStopWords); }
public SceneData CreateSceneData(string scene_name, TextAsset text_asset) { //IL_012e: Unknown result type (might be due to invalid IL or missing references) try { CSVReader cSVReader = new CSVReader(text_asset.get_text(), "name,type,useRes,loadRes,appVer,evName,evTo,retBtn,strKey,strJP", true); SceneData sceneData = new SceneData(); sceneData.sceneName = scene_name; SectionData sectionData = null; string text = null; while (cSVReader.NextLine()) { string value = string.Empty; string value2 = string.Empty; string value3 = string.Empty; string value4 = string.Empty; string value5 = string.Empty; string value6 = string.Empty; string value7 = string.Empty; int value8 = 0; string value9 = string.Empty; string value10 = string.Empty; cSVReader.Pop(ref value); cSVReader.Pop(ref value2); cSVReader.Pop(ref value3); cSVReader.Pop(ref value4); cSVReader.Pop(ref value5); cSVReader.Pop(ref value6); cSVReader.Pop(ref value7); cSVReader.Pop(ref value8); cSVReader.Pop(ref value9); cSVReader.Pop(ref value10); if (value.Length > 0) { sectionData = new SectionData(); if (value == "SCENE") { value = scene_name + "Scene"; } sectionData.sectionName = value; if (text != null && value == text) { sectionData.isTop = true; text = null; } if (value2.Length == 0) { throw new UnityException("scene table parse error"); } sectionData.typeParams = value2.Split(new char[1] { ':' }, StringSplitOptions.RemoveEmptyEntries); try { sectionData.type = (GAME_SECTION_TYPE)(int)Enum.Parse(typeof(GAME_SECTION_TYPE), sectionData.typeParams[0]); } catch (Exception) { sectionData.type = GAME_SECTION_TYPE.COMMON_DIALOG; } sectionData.backButtonIndex = value8; sceneData.sectionList.Add(sectionData); } if (value3.Length > 0) { sectionData.useResourceList.Add(value3); } if (value4.Length > 0) { if (sectionData.preloadResourceList == null) { sectionData.preloadResourceList = new List <string>(); } sectionData.preloadResourceList.Add(value4); } if (value6.Length > 0 || value7.Length > 0) { EventData eventData = new EventData(); eventData.appVer = value5; eventData.eventName = value6; if (sectionData.type == GAME_SECTION_TYPE.SCENE && value6.Length == 0 && value7.Length > 0) { text = value7; } string[] array = value7.Split(':'); eventData.toSectionName = array[0]; eventData.closeType = UITransition.TYPE.CLOSE; eventData.openType = UITransition.TYPE.OPEN; int i = 1; for (int num = array.Length; i < num; i++) { string text2 = array[i]; if (text2.Length == 3 && text2[1] == '>') { if (text2[0] == 'c') { eventData.closeType = UITransition.GetType(text2[2]); } else if (text2[0] == 'o') { eventData.openType = UITransition.GetType(text2[2]); } } } if (sectionData.eventDataList == null) { sectionData.eventDataList = new List <EventData>(); } sectionData.eventDataList.Add(eventData); } if (value9.Length > 0 || value10.Length > 0) { TextData textData = new TextData(); textData.key = value9; textData.text = value10; if (sectionData.textList == null) { sectionData.textList = new List <TextData>(); } sectionData.textList.Add(textData); } } sceneDataTable.Add(scene_name, sceneData); return(sceneData); IL_038e: SceneData result; return(result); } catch (Exception exc) { Log.Exception(exc); return(null); IL_03a4: SceneData result; return(result); } }
public CodeData CreateCodeData(TextCovertedData data, EventCodeScriptable scr) { if (data == null) { return(new EndCode()); } if (CheckChain(data)) { return(this); } CodeData result = null; switch (data._head) { case "": case "name": //name[name] result = new TextData(data); break; case "branch": //branch \nbranchName \n $#1... result = new BranchCode(data); break; case "flag": //flag[flagName] 5 result = new FlagCode(data); break; case "item": //item[itemName] 1 result = new ItemCode(data); break; case "map": //map[mapName] result = new MapCode(data); break; case "image": //image[setName,num] back (center) result = new ImageCode(data); break; case "music": //music[setName,0] result = new AudioCode(data); break; case "battle": //battle[enemySetName] result = new BattleCode(data); break; case "load": //load[black] 500 result = new LoadCode(data); break; case "wait": //wait[500] result = new WaitCode(data); break; default: return(null); } result._targetScr = scr; return(result); }
public static void Example() { // Create a new ML context, for ML.NET operations. It can be used for // exception tracking and logging, as well as the source of randomness. var mlContext = new MLContext(); // Create an empty list as the dataset. The 'ApplyWordEmbedding' does // not require training data as the estimator ('WordEmbeddingEstimator') // created by 'ApplyWordEmbedding' API is not a trainable estimator. // The empty list is only needed to pass input schema to the pipeline. var emptySamples = new List <TextData>(); // Convert sample list to an empty IDataView. var emptyDataView = mlContext.Data.LoadFromEnumerable(emptySamples); // A pipeline for converting text into a 150-dimension embedding vector // using pretrained 'SentimentSpecificWordEmbedding' model. The // 'ApplyWordEmbedding' computes the minimum, average and maximum values // for each token's embedding vector. Tokens in // 'SentimentSpecificWordEmbedding' model are represented as // 50 -dimension vector. Therefore, the output is of 150-dimension [min, // avg, max]. // // The 'ApplyWordEmbedding' API requires vector of text as input. // The pipeline first normalizes and tokenizes text then applies word // embedding transformation. var textPipeline = mlContext.Transforms.Text.NormalizeText("Text") .Append(mlContext.Transforms.Text.TokenizeIntoWords("Tokens", "Text")) .Append(mlContext.Transforms.Text.ApplyWordEmbedding("Features", "Tokens", WordEmbeddingEstimator.PretrainedModelKind .SentimentSpecificWordEmbedding)); // Fit to data. var textTransformer = textPipeline.Fit(emptyDataView); // Create the prediction engine to get the embedding vector from the // input text/string. var predictionEngine = mlContext.Model.CreatePredictionEngine <TextData, TransformedTextData>(textTransformer); // Call the prediction API to convert the text into embedding vector. var data = new TextData() { Text = "This is a great product. I would " + "like to buy it again." }; var prediction = predictionEngine.Predict(data); // Print the length of the embedding vector. Console.WriteLine($"Number of Features: {prediction.Features.Length}"); // Print the embedding vector. Console.Write("Features: "); foreach (var f in prediction.Features) { Console.Write($"{f:F4} "); } // Expected output: // Number of Features: 150 // Features: -1.2489 0.2384 -1.3034 -0.9135 -3.4978 -0.1784 -1.3823 -0.3863 -2.5262 -0.8950 ... }
void LoadAllAcupoints() { TextData.GetInstance().AllAcupoints = LoadAllLineToList("acupoint_name"); }
public string ToStringTextData(Encoding encoding) { return(String.Join(string.Empty, TextData.Select(c => c.ToString(encoding)))); }
public void OnTextChanged(DialogueFlow dialogue, TextData text, List <TextAnswerData> answers, SettingsData settings) { _behaviour = dialogue.Behaviour; // Select and open a skin if (settings.Skin == "") { settings.Skin = (dialogue.DefaultSkin != "") ? dialogue.DefaultSkin : DefaultSkin; } SelectSkin(settings.Skin); if (_activeSkin == null) { RunemarkDebug.Warning(settings.Skin + " skin doesn't exists in this canvas: " + gameObject.name); return; } // Stop the audio if currently playing if (_audioSource.isPlaying) { _audioSource.Stop(); } // Set the actor's name and portrait string name = text.Name; Sprite portrait = text.Portrait; _activeSkin.SetText(name, portrait, text.Text); _activeSkin.HideInputAnswer(); _activeSkin.HideAnswers(0); // Set the answers int cnt = 0; foreach (var a in answers) { if (a.UseCustomUI) { _activeSkin.SetCustomAnswer(a.UIElementName, a); } else if (answers.Count > cnt) { _activeSkin.SetAnswer(cnt, a); cnt++; } } // _activeSkin.HideAnswers(cnt); // Play Audio if any if (text.Audio != null) { _audioStopTime = text.AudioEndTime; _audioSource.clip = text.Audio; _audioSource.time = text.AudioStartTime; if (text.AudioDelay > 0) { _audioSource.PlayDelayed(text.AudioDelay); } else { _audioSource.Play(); } } // Set the timer if (_behaviour.Timer != null && cnt > 0) { _activeSkin.StartTimer(_behaviour.Timer.Seconds); } else { _activeSkin.HideTimer(); } }
public override bool Write(TextLocation start, TextLocation end, TextData replacement) { if (!CanWrite(start, end) || replacement == null) { throw new ArgumentException(); } var currentData = this.CurrentTextData; var newData = TextData.ApplyEdit(currentData, start, end, replacement); var newEnd = DetermineNewEnd(start, end, replacement); var newChange = new TextChange() { OldTextData = currentData, NewTextData = newData, Start = start, OldEnd = end, NewEnd = newEnd, Replacement = replacement }; if (this.lastChange == null) { this.firstChange = this.lastChange = newChange; } else { this.lastChange.NextChange = newChange; this.lastChange = newChange; } if (this.undoUnit != null) { this.undoUnit.AddChange(newChange); } return true; }
static void Main(string[] args) { Directory.CreateDirectory(".\\logs"); var logName = $".\\logs\\Implem.CodeDefiner_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.log"; Trace.Listeners.Add(new TextWriterTraceListener(logName)); Trace.Listeners.Add(new ConsoleTraceListener()); AppDomain.CurrentDomain.UnhandledException += (_, e) => { if (e.ExceptionObject is SqlException sqlException) { Consoles.Write($"UnhandledException: [{sqlException.Number}] {sqlException.Message}", Consoles.Types.Error, true); } else { Consoles.Write("UnhandledException: " + e.ExceptionObject, Consoles.Types.Error, true); } }; var argList = args.Select(o => o.Trim()); ValidateArgs(argList); var argHash = new TextData(argList.Skip(1).Join(string.Empty), '/', 1); var action = args[0]; var path = argHash.Get("p"); var target = argHash.Get("t"); Initializer.Initialize( path, assemblyVersion: Assembly.GetExecutingAssembly().GetName().Version.ToString(), codeDefiner: true, setSaPassword: argHash.ContainsKey("s"), setRandomPassword: argHash.ContainsKey("r")); switch (action) { case "_rds": ConfigureDatabase(); break; case "rds": ConfigureDatabase(); CreateDefinitionAccessorCode(); CreateMvcCode(target); break; case "_def": CreateDefinitionAccessorCode(); break; case "def": CreateDefinitionAccessorCode(); CreateMvcCode(target); break; case "mvc": CreateMvcCode(target); break; case "css": CreateCssCode(); break; case "backup": CreateSolutionBackup(); break; default: WriteErrorToConsole(args); break; } if (Consoles.ErrorCount > 0) { Consoles.Write( string.Format(DisplayAccessor.Displays.Get("CodeDefinerErrorCount"), Consoles.ErrorCount, Path.GetFullPath(logName)), Consoles.Types.Error); } else { Consoles.Write( DisplayAccessor.Displays.Get("CodeDefinerCompleted"), Consoles.Types.Success); } WaitConsole(args); }
bool IsLocationValid(TextData currentData, TextLocation loc) { if ((loc.Line >= 0) && (loc.Line < currentData.Lines.Count) && (loc.Index >= 0) && (loc.Index <= currentData.Lines[loc.Line].Length)) { return true; } return false; }
/// <summary> /// Migrates the objects. /// </summary> /// <param name="doWrite">If set to <c>true</c>, do write changes to the database.</param> /// <returns> /// The task. /// </returns> public async Task MigrateObjectsAsync(bool doWrite) { // Get the existing projects from MongoDB List <SFProject> existingProjects = this._realtimeService.QuerySnapshots <SFProject>().ToList(); // If we are testing, add the test projects if (!doWrite) { existingProjects.AddRange(this._testProjectCollection); } // This is the mapping for update the TextData identifiers // The key is the target project id, the value is the new source project id Dictionary <string, string> sourceMapping = new Dictionary <string, string>(); // Connect to the realtime service using IConnection connection = await this._realtimeService.ConnectAsync(); // Iterate over every project in database foreach (var project in existingProjects) { // Update ProjectRef value string?sourceParatextId = project.TranslateConfig?.Source?.ParatextId; if (!string.IsNullOrWhiteSpace(sourceParatextId)) { // Get the source project SFProject sourceProject = existingProjects.FirstOrDefault(p => p.ParatextId == sourceParatextId); if (sourceProject != null) { // Update the database Program.Log($"Project {project.Id} $.TranslateConfig.Source.ProjectRef = '{sourceProject.Id}'"); if (doWrite) { // Set the ProjectRef var projectDoc = await connection.FetchAsync <SFProject>(project.Id); await projectDoc.SubmitJson0OpAsync(op => { op.Set(p => p.TranslateConfig.Source.ProjectRef, sourceProject.Id); }); } // Record the source mapping sourceMapping.Add(project.Id, sourceProject.Id); } else { Program.Log($"Error Migrating {project.Id} - Source {sourceParatextId} is missing from MongoDB!"); } } } // Get the Textdata collection string collectionName = this._realtimeService.GetCollectionName <TextData>(); IMongoCollection <TextData> collection = this._database.GetCollection <TextData>(collectionName); // Get the existing textdata object ids from MongoDB List <string> textIds = collection.AsQueryable().Select(t => t.Id).ToList(); if (!doWrite) { // Add the test text ids, if we are testing textIds = textIds.Concat(this._testTextDataIdCollection).Distinct().ToList(); } List <string> sourceTextIds = textIds.Where(t => t.EndsWith(":source", StringComparison.Ordinal)).ToList(); // Iterate over every text id in database foreach (string textId in sourceTextIds) { // Get the TextData from the database TextData?text = await collection .Find(Builders <TextData> .Filter.Eq("_id", textId)) .SingleOrDefaultAsync(); // If we are testing, see if we have an id in the our test collection if (!doWrite && text == null && this._testTextDataIdCollection.Contains(textId)) { // Build a hollow text data object for test purposes text = new TextData() { Id = textId }; } // If we have the specified id in the database if (text != null) { // Create with new _id for source text, deleting the old one // You cannot rename _id's, and the client will download a new object with the new id anyway string oldId = text.Id; string[] textIdParts = oldId.Split(':', StringSplitOptions.RemoveEmptyEntries); if (textIdParts.Length == 4 && textIdParts.Last() == "source") { string targetId = textIdParts.First(); if (sourceMapping.ContainsKey(targetId)) { text.Id = $"{sourceMapping[targetId]}:{textIdParts[1]}:{textIdParts[2]}:target"; if (!textIds.Contains(text.Id)) { textIds.Add(text.Id); Program.Log($"Rename TextData {oldId} to {text.Id}"); if (doWrite) { // NOTE: You cannot rename _id in MongoDB! // Delete from ShareDB IDocument <TextData> oldTextDoc = connection.Get <TextData>(oldId); await oldTextDoc.FetchAsync(); if (oldTextDoc.IsLoaded) { await oldTextDoc.DeleteAsync(); } // Remove from MongoDB await this.DeleteDocsAsync("texts", oldId); // Add the new text document via the real time service await connection.CreateAsync(text.Id, text); } } else { // Remove the source, as the it already exists as a target Program.Log($"TextData {text.Id} already exists, deleting {oldId}"); if (doWrite) { // Delete from ShareDB IDocument <TextData> oldTextDoc = connection.Get <TextData>(oldId); await oldTextDoc.FetchAsync(); if (oldTextDoc.IsLoaded) { await oldTextDoc.DeleteAsync(); } // Remove from MongoDB await this.DeleteDocsAsync("texts", oldId); } } } else { Program.Log($"Error Migrating TextData {text.Id} - Missing Source Mapping"); } } else { Program.Log($"Error Migrating TextData {text.Id} - Incorrect Identifier Format"); } } else { Program.Log($"Error Migrating TextData {textId} - Could Not Load From MongoDB"); } } }
public IActionResult ExcelExport() { // https://steemit.com/utopian-io/@haig/how-to-create-excel-spreadsheets-using-npoi var workbook = new HSSFWorkbook(); var sheet = workbook.CreateSheet("Sheet 1"); IFont fontBold = workbook.CreateFont(); fontBold.Boldweight = (short)FontBoldWeight.Bold; var headerCellStyle = workbook.CreateCellStyle(); headerCellStyle.SetFont(fontBold); var header = sheet.CreateRow(0); ICell col1 = header.CreateCell(0); col1.CellStyle = headerCellStyle; col1.SetCellValue("Fullname"); ICell col2 = header.CreateCell(1); col2.CellStyle = headerCellStyle; col2.SetCellValue("Country"); ICell col3 = header.CreateCell(2); col3.CellStyle = headerCellStyle; col3.SetCellValue("Email"); ICell col4 = header.CreateCell(3); col4.CellStyle = headerCellStyle; col4.SetCellValue("Numbers"); ICell col5 = header.CreateCell(4); col5.CellStyle = headerCellStyle; col5.SetCellValue("Datetime"); ICell col6 = header.CreateCell(5); col6.CellStyle = headerCellStyle; col6.SetCellValue("Sentence"); var currencyCellStyle = workbook.CreateCellStyle(); currencyCellStyle.Alignment = HorizontalAlignment.Right; currencyCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("₺#.##0,00");; int length = 50; for (int i = 0; i < length; i++) { var row = sheet.CreateRow(i + 1); row.CreateCell(0).SetCellValue(NameData.GetFullName()); row.CreateCell(1).SetCellValue(PlaceData.GetCountry()); row.CreateCell(2).SetCellValue(NetworkData.GetEmail()); ICell numberCell = row.CreateCell(3); numberCell.CellStyle = currencyCellStyle; numberCell.SetCellValue(NumberData.GetDouble() * 1000); row.CreateCell(4).SetCellValue(DateTimeData.GetDatetime().ToShortDateString()); row.CreateCell(5).SetCellValue(TextData.GetSentence()); } var totalRow = sheet.CreateRow(length + 1); ICell totalCell = totalRow.CreateCell(3); ICellStyle totalCellStyle = workbook.CreateCellStyle(); totalCellStyle.CloneStyleFrom(sheet.GetRow(length).GetCell(3).CellStyle); totalCell.CellStyle = totalCellStyle; totalCell.CellStyle.SetFont(fontBold); totalCell.SetCellType(CellType.Formula); totalCell.CellFormula = $"SUM(D2:D{length + 1})"; // Headercell den sonrası. string root = _environment.WebRootPath; string folder = Path.Combine(root, "Excels"); string filename = "f_" + Guid.NewGuid().ToString() + ".xls"; string file = Path.Combine(folder, filename); if (Directory.Exists(folder) == false) { Directory.CreateDirectory(folder); } using (var fileStream = new FileStream(file, FileMode.Create)) { workbook.Write(fileStream); } return(File("~/Excels/" + filename, "application/vnd.ms-excel")); }
/// <summary> /// Creates an internal test project. /// </summary> /// <param name="sourceId">The source project/resource identifier.</param> /// <param name="targetId">The target project identifier. /// This is the project that will reference this project/resource a source.</param> /// <returns>THe task</returns> /// <exception cref="DataNotFoundException"> /// The target project does not exist /// or /// The user does not exist. /// </exception> /// <remarks> /// This is only to be used on test runs! /// </remarks> internal async Task CreateInternalTestProjectAsync(string sourceId, string targetId) { if (!this._testProjectCollection.Any(p => p.ParatextId == sourceId) && !string.IsNullOrWhiteSpace(sourceId)) { // Create the test project SFProject testProject = new SFProject { Id = ObjectId.GenerateNewId().ToString(), ParatextId = sourceId, }; this._testProjectCollection.Add(testProject); // Load the source project from the target project's source directory (it is not moved in test mode) ScrText?scrText = SourceScrTextCollection.FindById("admin", targetId); if (scrText != null) { // Create the test text objects for all of the books foreach (int bookNum in scrText.Settings.BooksPresentSet.SelectedBookNumbers) { string usfm = scrText.GetText(bookNum); string bookText = UsfmToUsx.ConvertToXmlString(scrText, bookNum, usfm, false); var usxDoc = XDocument.Parse(bookText); Dictionary <int, ChapterDelta> deltas = this._deltaUsxMapper.ToChapterDeltas(usxDoc).ToDictionary(cd => cd.Number); var chapters = new List <Chapter>(); foreach (KeyValuePair <int, ChapterDelta> kvp in deltas) { this._testTextDataIdCollection.Add(TextData.GetTextDocId(testProject.Id, bookNum, kvp.Key)); } } } else { Program.Log($"Test Mode Error Migrating TextData For {sourceId} - Could Not Load From Filesystem!"); } // See that at least one user in the target project has permission to create the source project var targetProject = this._realtimeService.QuerySnapshots <SFProject>().FirstOrDefault(p => p.ParatextId == targetId); if (targetProject == null) { throw new DataNotFoundException("The target project does not exist"); } // Get the highest ranked users for this project, that probably have source access string[] userIds = targetProject.UserRoles .Where(ur => ur.Value == SFProjectRole.Administrator || ur.Value == SFProjectRole.Translator) .OrderBy(ur => ur.Value) .Select(ur => ur.Key) .ToArray(); bool someoneCanAccessSourceProject = false; foreach (string userId in userIds) { Attempt <UserSecret> userSecretAttempt = await _userSecrets.TryGetAsync(userId); if (!userSecretAttempt.TryResult(out UserSecret userSecret)) { throw new DataNotFoundException("The user does not exist."); } // We check projects first, in case it is a project IReadOnlyList <ParatextProject> ptProjects = await _paratextService.GetProjectsAsync(userSecret); if (ptProjects.Any(p => p.ParatextId == sourceId)) { someoneCanAccessSourceProject = true; break; } } if (!someoneCanAccessSourceProject) { Program.Log($"Test Mode Error Creating {sourceId} - Nobody In The Target Project Has Access!"); } } }
public void Generate() { var random = new Random(); client.PutIndex(new RavenDocumentsByEntityName()); client.PutIndex(new OrdersByCompany()); client.PutIndex(new OrdersTotals()); client.PutIndex(new ProductSales()); client.PutIndex(new OrdersByEmployeeAndCompany()); client.PutIndex(new OrdersByEmployeeAndCompanyReduce()); var nextOrderId = 1; var nextCompanyId = 1; var nextProductId = 1; var nextEmployeeId = 1; for (var it = 0; it < numberOfIterations; it++) { var entities = new List <object>(); for (var i = 0; i < NumberOfOrdersPerIteration; i++) { entities.Add(new Order { Id = "orders/" + nextOrderId++, Company = "companies/" + random.Next(1, ExpectedNumberOfCompanies - 1), Lines = CollectionData.GetElement(10, new List <OrderLine> { new OrderLine { Product = "products/" + random.Next(1, ExpectedNumberOfProducts - 1), Quantity = random.Next(1, 100), PricePerUnit = random.Next(1000) } }).ToList(), Employee = "employees/" + random.Next(1, ExpectedNumberOfEmployees - 1), OrderedAt = DateTimeData.GetDatetime(), RequireAt = DateTime.UtcNow.AddDays(7), ShipTo = new Address { Country = PlaceData.GetCountry(), City = PlaceData.GetCity(), PostalCode = PlaceData.GetZipCode(), Line1 = PlaceData.GetStreetName() } }); } for (var i = 0; i < NumberOfCompaniesPerIteration; i++) { entities.Add(new Company { Id = "companies/" + nextCompanyId++, Name = NameData.GetCompanyName(), Fax = PhoneNumberData.GetInternationalPhoneNumber(), Address = new Address { Country = PlaceData.GetCountry(), City = PlaceData.GetCity(), PostalCode = PlaceData.GetZipCode(), Line1 = PlaceData.GetStreetName() } }); } for (var i = 0; i < NumberOfEmployeesPerIteration; i++) { entities.Add(new Employee { Id = "employees/" + nextEmployeeId++, Birthday = DateTimeData.GetDatetime(), FirstName = NameData.GetFirstName(), LastName = NameData.GetSurname(), HomePhone = PhoneNumberData.GetPhoneNumber(), HiredAt = DateTimeData.GetDatetime(), Address = new Address { Country = PlaceData.GetCountry(), City = PlaceData.GetCity(), PostalCode = PlaceData.GetZipCode(), Line1 = PlaceData.GetStreetName() } }); } for (var i = 0; i < NumberOfProductsPerIteration; i++) { entities.Add(new Product { Id = "products/" + nextProductId++, Category = TextData.GetAlphabetical(5), Name = NameData.GetSurname(), Discontinued = BooleanData.GetBoolean(), PricePerUnit = NumberData.GetNumber() }); } client.PutEntities(entities); } }
public abstract bool Write(TextLocation start, TextLocation end, TextData replacement);
private static AllTypesModel GenerateSimpleModel(Random random, int min, int max) { var itemToAdd = new AllTypesModel { Long = NumberData.GetNumber(min, max), LongNullable = RandomiseNullable(NumberData.GetNumber(min, max)), #if USE_UTYPES ULong = (ulong)NumberData.GetNumber(0, max), ULongNullable = RandomiseNullable((ulong)NumberData.GetNumber(0, max)), #else ULong = (long)NumberData.GetNumber(0, max), ULongNullable = (long?)RandomiseNullable(NumberData.GetNumber(0, max)), #endif Integer = random.Next(min, max), IntegerNullable = RandomiseNullable(FakeData.NumberData.GetNumber(min, max)), #if USE_UTYPES UInt = (uint)NumberData.GetNumber(0, max), UIntNullable = (uint?)RandomiseNullable(NumberData.GetNumber(0, max)), #else UInt = (int)NumberData.GetNumber(0, max), UIntNullable = (int?)RandomiseNullable(NumberData.GetNumber(0, max)), #endif DoubleProperty = NumberData.GetDouble(), DoubleNullable = RandomiseNullable(NumberData.GetDouble()), Float = (float)NumberData.GetDouble(), FloatNullable = RandomiseNullable((float)NumberData.GetDouble()), DecimalProperty = (decimal)NumberData.GetDouble(), DecimalNullable = (decimal?)RandomiseNullable(NumberData.GetDouble()), Short = (short)NumberData.GetNumber(min, max), ShortNullable = (short?)(NumberData.GetNumber(min, max)), #if USE_UTYPES UShort = (ushort)NumberData.GetNumber(0, max), UShortNullable = (ushort?)RandomiseNullable(NumberData.GetNumber(0, max)), #else UShort = (short)NumberData.GetNumber(0, max), UShortNullable = (short?)RandomiseNullable(NumberData.GetNumber(0, max)), #endif ByteProperty = RandomByte(), ByteNullable = RandomiseNullable(RandomByte()), #if USE_STYPES SByteProperty = RandomSByte(), SByteNullable = RandomiseNullable(RandomSByte()), #else SByteProperty = RandomByte(), SByteNullable = RandomiseNullable(RandomByte()), #endif #if USE_CHARTYPE CharProperty = FakeData.TextData.GetAlphabetical(1)[0], CharNullable = RandomiseNullable(FakeData.TextData.GetAlphabetical(1)[0]), #else CharProperty = FakeData.TextData.GetAlphabetical(1)[0].ToString(), CharNullable = RandomiseNullable(TextData.GetAlphaNumeric(1), 0.3), #endif BooleanProperty = BooleanData.GetBoolean(), BooleanNullable = RandomiseNullable(BooleanData.GetBoolean()), StringProperty = RandomiseNullable(TextData.GetAlphaNumeric(NumberData.GetNumber(0, 20)), 0.3), DateTimeProperty = RandomDate(max), DateTimeNullable = RandomiseNullable(RandomDate(max)), #if USE_DTOFFSET DateTimeOffsetProperty = RandomDateTimeOffset(max), DateTimeOffsetNullable = RandomiseNullable(RandomDateTimeOffset(max)) #else DateTimeOffsetProperty = RandomDate(max), DateTimeOffsetNullable = RandomiseNullable(RandomDate(max)), #endif }; return(itemToAdd); }
//------------------------------------------------------------------------------ // Explicit Activation // This entry point is used to activate the application explicitly //------------------------------------------------------------------------------ public static int Main(string[] args) { int retValue = 0; try { theProgram = new Program(); Session theSession = Session.GetSession(); Part workPart = theSession.Parts.Work; Part displayPart = theSession.Parts.Display; DefineVariable.Is_Local = Environment.GetEnvironmentVariable("UGII_ENV_FILE"); if (DefineVariable.Is_Local != "") { //取得本機IQC.xls路徑 DefineVariable.IQCPath = string.Format(@"{0}\{1}\{2}", Path.GetDirectoryName(displayPart.FullPath), "MODEL", "IQC.xls"); } //取得料號 string PartNo = Path.GetFileNameWithoutExtension(displayPart.FullPath); //取得材質 string MaterialStr = ""; try { MaterialStr = displayPart.GetStringAttribute("MATERIALPOS"); } catch (System.Exception ex) { MaterialStr = ""; } int SheetCount = 0; NXOpen.Tag[] SheetTagAry = null; theUfSession.Draw.AskDrawings(out SheetCount, out SheetTagAry); DefineVariable.DicDimenData = new Dictionary <string, TextData>(); for (int i = 0; i < SheetCount; i++) { //打開Sheet並記錄所有OBJ NXOpen.Drawings.DrawingSheet CurrentSheet = (NXOpen.Drawings.DrawingSheet)NXObjectManager.Get(SheetTagAry[i]); CurrentSheet.Open(); if (i == 0) { //記錄第一張Sheet DefineVariable.FirstDrawingSheet = CurrentSheet; } DisplayableObject[] SheetObj = CurrentSheet.View.AskVisibleObjects(); foreach (DisplayableObject singleObj in SheetObj) { TextData cTextData = new TextData(); string singleObjType = singleObj.GetType().ToString(); string IQC_Gauge = "", BallonNum = "", Frequency = "", Location = ""; string[] mainText; string[] dualText; #region 取IQC共用屬性(泡泡值、檢具名稱、檢驗頻率、泡泡所在區域),如果都沒屬性就找下一個 try { IQC_Gauge = singleObj.GetStringAttribute(CaxME.DimenAttr.IQC_Gauge); BallonNum = singleObj.GetStringAttribute(CaxME.DimenAttr.BallonNum); Frequency = singleObj.GetStringAttribute(CaxME.DimenAttr.IQC_Freq); Location = singleObj.GetStringAttribute(CaxME.DimenAttr.BallonLocation); } catch (System.Exception ex) { IQC_Gauge = ""; } if (IQC_Gauge == "") { continue; } #endregion #region 紀錄共用屬性(泡泡值、檢具名稱、檢驗頻率、泡泡所在區域) //取得泡泡值 cTextData.BallonNum = BallonNum; //取得檢具名稱 cTextData.Gauge = IQC_Gauge; //取得檢驗頻率 cTextData.Frequency = Frequency; //取得泡泡所在區域 cTextData.Location = Location; #endregion if (singleObjType == "NXOpen.Annotations.VerticalDimension") { #region VerticalDimension取Text cTextData.Type = "NXOpen.Annotations.VerticalDimension"; NXOpen.Annotations.VerticalDimension temp = (NXOpen.Annotations.VerticalDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.PerpendicularDimension") { #region PerpendicularDimension取Text cTextData.Type = "NXOpen.Annotations.PerpendicularDimension"; NXOpen.Annotations.PerpendicularDimension temp = (NXOpen.Annotations.PerpendicularDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.MinorAngularDimension") { #region MinorAngularDimension取Text cTextData.Type = "NXOpen.Annotations.MinorAngularDimension"; NXOpen.Annotations.MinorAngularDimension temp = (NXOpen.Annotations.MinorAngularDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.RadiusDimension") { #region MinorAngularDimension取Text cTextData.Type = "NXOpen.Annotations.RadiusDimension"; NXOpen.Annotations.RadiusDimension temp = (NXOpen.Annotations.RadiusDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.HorizontalDimension") { #region HorizontalDimension取Text cTextData.Type = "NXOpen.Annotations.HorizontalDimension"; NXOpen.Annotations.HorizontalDimension temp = (NXOpen.Annotations.HorizontalDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } if (temp.ToleranceType.ToString() == "BilateralTwoLines") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = temp.LowerMetricToleranceValue.ToString(); } if (temp.ToleranceType.ToString() == "UnilateralAbove") { cTextData.TolType = "UnilateralAbove"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = "0"; } if (temp.ToleranceType.ToString() == "UnilateralBelow") { cTextData.TolType = "UnilateralBelow"; cTextData.UpperTol = "0"; cTextData.LowerTol = temp.LowerMetricToleranceValue.ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.IdSymbol") { #region IdSymbol取Text cTextData.Type = "NXOpen.Annotations.IdSymbol"; NXOpen.Annotations.IdSymbol temp = (NXOpen.Annotations.IdSymbol)singleObj; #endregion } else if (singleObjType == "NXOpen.Annotations.Note") { #region Note取Text cTextData.Type = "NXOpen.Annotations.Note"; NXOpen.Annotations.Note temp = (NXOpen.Annotations.Note)singleObj; //判斷是否由CAX產生的Note string createby = ""; try { createby = temp.GetStringAttribute("Createby"); } catch (System.Exception ex) { createby = ""; } if (createby == "") { string tempStr = temp.GetText()[0].Replace("<F2>", ""); tempStr = tempStr.Replace("<F>", ""); cTextData.MainText = tempStr; } else { cTextData.MainText = temp.GetText()[0]; } #endregion } else if (singleObjType == "NXOpen.Annotations.DraftingFcf") { #region DraftingFcf取Text NXOpen.Annotations.DraftingFcf temp = (NXOpen.Annotations.DraftingFcf)singleObj; CaxME.FcfData sFcfData = new CaxME.FcfData(); CaxME.GetFcfData(temp, out sFcfData); cTextData.Type = "NXOpen.Annotations.DraftingFcf"; cTextData.Characteristic = sFcfData.Characteristic; cTextData.ZoneShape = sFcfData.ZoneShape; cTextData.ToleranceValue = sFcfData.ToleranceValue; cTextData.MaterialModifier = sFcfData.MaterialModifier; cTextData.PrimaryDatum = sFcfData.PrimaryDatum; cTextData.PrimaryMaterialModifier = sFcfData.PrimaryMaterialModifier; cTextData.SecondaryDatum = sFcfData.SecondaryDatum; cTextData.SecondaryMaterialModifier = sFcfData.SecondaryMaterialModifier; cTextData.TertiaryDatum = sFcfData.TertiaryDatum; cTextData.TertiaryMaterialModifier = sFcfData.TertiaryMaterialModifier; #endregion } else if (singleObjType == "NXOpen.Annotations.Label") { #region Label取Text cTextData.Type = "NXOpen.Annotations.Label"; NXOpen.Annotations.Label temp = (NXOpen.Annotations.Label)singleObj; cTextData.MainText = temp.GetText()[0]; #endregion } else if (singleObjType == "NXOpen.Annotations.DraftingDatum") { #region DraftingDatum取Text cTextData.Type = "NXOpen.Annotations.DraftingDatum"; NXOpen.Annotations.DraftingDatum temp = (NXOpen.Annotations.DraftingDatum)singleObj; #endregion } else if (singleObjType == "NXOpen.Annotations.DiameterDimension") { #region DiameterDimension取Text cTextData.Type = "NXOpen.Annotations.DiameterDimension"; NXOpen.Annotations.DiameterDimension temp = (NXOpen.Annotations.DiameterDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.AngularDimension") { #region AngularDimension取Text cTextData.Type = "NXOpen.Annotations.AngularDimension"; NXOpen.Annotations.AngularDimension temp = (NXOpen.Annotations.AngularDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.CylindricalDimension") { #region CylindricalDimension取Text cTextData.Type = "NXOpen.Annotations.CylindricalDimension"; NXOpen.Annotations.CylindricalDimension temp = (NXOpen.Annotations.CylindricalDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0]; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } if (temp.ToleranceType.ToString() == "BilateralTwoLines") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = temp.LowerMetricToleranceValue.ToString(); } if (temp.ToleranceType.ToString() == "UnilateralAbove") { cTextData.TolType = "UnilateralAbove"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = "0"; } if (temp.ToleranceType.ToString() == "UnilateralBelow") { cTextData.TolType = "UnilateralBelow"; cTextData.UpperTol = "0"; cTextData.LowerTol = temp.LowerMetricToleranceValue.ToString(); } #endregion } else if (singleObjType == "NXOpen.Annotations.ChamferDimension") { #region ChamferDimension取Text cTextData.Type = "NXOpen.Annotations.ChamferDimension"; NXOpen.Annotations.ChamferDimension temp = (NXOpen.Annotations.ChamferDimension)singleObj; temp.GetDimensionText(out mainText, out dualText); if (mainText.Length > 0) { cTextData.MainText = mainText[0] + "X" + "45" + "<$s>"; } if (temp.GetAppendedText().GetBeforeText().Length > 0) { cTextData.BeforeText = temp.GetAppendedText().GetBeforeText()[0].ToString(); } if (temp.GetAppendedText().GetAfterText().Length > 0) { cTextData.AfterText = temp.GetAppendedText().GetAfterText()[0].ToString(); } if (temp.GetAppendedText().GetAboveText().Length > 0) { cTextData.AboveText = temp.GetAppendedText().GetAboveText()[0].ToString(); } if (temp.GetAppendedText().GetBelowText().Length > 0) { cTextData.BelowText = temp.GetAppendedText().GetBelowText()[0].ToString(); } if (temp.ToleranceType.ToString() == "BilateralOneLine") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = (-1 * temp.UpperMetricToleranceValue).ToString(); } if (temp.ToleranceType.ToString() == "BilateralTwoLines") { cTextData.TolType = "BilateralOneLine"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = temp.LowerMetricToleranceValue.ToString(); } if (temp.ToleranceType.ToString() == "UnilateralAbove") { cTextData.TolType = "UnilateralAbove"; cTextData.UpperTol = temp.UpperMetricToleranceValue.ToString(); cTextData.LowerTol = "0"; } if (temp.ToleranceType.ToString() == "UnilateralBelow") { cTextData.TolType = "UnilateralBelow"; cTextData.UpperTol = "0"; cTextData.LowerTol = temp.LowerMetricToleranceValue.ToString(); } #endregion } //計算泡泡總數 DefineVariable.BallonCount++; DefineVariable.DicDimenData[BallonNum] = cTextData; } } //設定輸出路徑--Server string OperNum = Regex.Replace(Path.GetFileNameWithoutExtension(displayPart.FullPath).Split('_')[1], "[^0-9]", ""); string Local_Folder_OIS = string.Format(@"{0}\{1}\{2}", Path.GetDirectoryName(displayPart.FullPath), "OP" + OperNum, "OIS"); if (!File.Exists(Local_Folder_OIS)) { System.IO.Directory.CreateDirectory(Local_Folder_OIS); } string[] FolderFile = System.IO.Directory.GetFileSystemEntries(Local_Folder_OIS, "*.xls"); List <string> ListFolderFileWithIPQC = new List <string>(); foreach (string i in FolderFile) { if (i.Contains("IQC")) { ListFolderFileWithIPQC.Add(i); } } string OutputPath = string.Format(@"{0}\{1}", Local_Folder_OIS, Path.GetFileNameWithoutExtension(displayPart.FullPath) + "_" + "IQC" + "_" + (ListFolderFileWithIPQC.Count + 1) + ".xls"); //檢查PC有無Excel在執行 foreach (var item in Process.GetProcesses()) { if (item.ProcessName == "EXCEL") { CaxLog.ShowListingWindow("請先關閉所有Excel再重新執行輸出,如沒有EXCEL在執行,請開啟工作管理員關閉背景EXCEL"); return(retValue); } else { continue; } } Excel.ApplicationClass x = new Excel.ApplicationClass(); Excel.Workbook book = null; Excel.Worksheet sheet = null; Excel.Range oRng = null; try { x.Visible = false; if (DefineVariable.Is_Local != "") { if (File.Exists(DefineVariable.IQCPath)) { book = x.Workbooks.Open(DefineVariable.IQCPath); } else { book = x.Workbooks.Open(@"D:\IQC.xls"); } } else { book = x.Workbooks.Open(@"D:\IQC.xls"); } sheet = (Excel.Worksheet)book.Sheets[1]; //由檢驗總數開啟符合總數的頁數 int needSheetNo = (DefineVariable.BallonCount / 12); int needSheetNo_Reserve = (DefineVariable.BallonCount % 12); if (needSheetNo_Reserve != 0) { needSheetNo++; } for (int i = 1; i < needSheetNo; i++) { sheet.Copy(System.Type.Missing, x.Workbooks[1].Worksheets[1]); } //更改每一個Sheet的名稱與頁數 for (int i = 0; i < book.Worksheets.Count; i++) { sheet = (Excel.Worksheet)book.Sheets[i + 1]; if (i == 0 && book.Worksheets.Count > 1) { sheet.Name = PartNo; //oRng = (Excel.Range)sheet.Cells[5, 17]; //oRng.Value = oRng.Value.ToString().Replace("1/1", "1/" + (book.Worksheets.Count).ToString()); } else { sheet.Name = PartNo + "(" + (i + 1) + ")"; //oRng = (Excel.Range)sheet.Cells[5, 17]; //string temp = (i + 1).ToString(); //oRng.Value = oRng.Value.ToString().Replace("1/1", temp + "/" + (book.Worksheets.Count).ToString()); } } //填表 int ExcelSequenceNo = -1; for (int i = 1; i < 1000; i++) { ExcelSequenceNo++; TextData cTextData; DefineVariable.DicDimenData.TryGetValue(i.ToString(), out cTextData); if (cTextData == null) { ExcelSequenceNo--; continue; } RowColumn sRowColumn; DefineVariable.GetExcelRowColumn(ExcelSequenceNo, out sRowColumn); int currentSheet_Value = (ExcelSequenceNo / 12); int currentSheet_Reserve = (ExcelSequenceNo % 12); if (currentSheet_Value == 0) { sheet = (Excel.Worksheet)book.Sheets[1]; } else { sheet = (Excel.Worksheet)book.Sheets[currentSheet_Value + 1]; } oRng = (Excel.Range)sheet.Cells; if (cTextData.Type == "NXOpen.Annotations.DraftingFcf") { #region DraftingFcf填資料 if (cTextData.Characteristic != "") { oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = DefineVariable.GetCharacteristicSymbol(cTextData.Characteristic); //oRng[sRowColumn.CharacteristicRow, sRowColumn.CharacteristicColumn] = DefineVariable.GetCharacteristicSymbol(cTextData.Characteristic); } if (cTextData.ZoneShape != "") { oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + DefineVariable.GetZoneShapeSymbol(cTextData.ZoneShape); //oRng[sRowColumn.ZoneShapeRow, sRowColumn.ZoneShapeColumn] = DefineVariable.GetZoneShapeSymbol(cTextData.ZoneShape); } oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.ToleranceValue; //oRng[sRowColumn.ToleranceValueRow, sRowColumn.ToleranceValueColumn] = cTextData.ToleranceValue; if (cTextData.MaterialModifier != "" & cTextData.MaterialModifier != "None") { string ValueStr = cTextData.MaterialModifier; if (ValueStr == "LeastMaterialCondition") { ValueStr = "l"; } else if (ValueStr == "MaximumMaterialCondition") { ValueStr = "m"; } else if (ValueStr == "RegardlessOfFeatureSize") { ValueStr = "s"; } oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + ValueStr; //oRng[sRowColumn.MaterialModifierRow, sRowColumn.MaterialModifierColumn] = ValueStr; } //Primary oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.PrimaryDatum; //oRng[sRowColumn.PrimaryDatumRow, sRowColumn.PrimaryDatumColumn] = cTextData.PrimaryDatum; if (cTextData.PrimaryMaterialModifier != "" & cTextData.PrimaryMaterialModifier != "None") { string ValueStr = cTextData.PrimaryMaterialModifier; if (ValueStr == "LeastMaterialCondition") { ValueStr = "l"; } else if (ValueStr == "MaximumMaterialCondition") { ValueStr = "m"; } else if (ValueStr == "RegardlessOfFeatureSize") { ValueStr = "s"; } oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + ValueStr; //oRng[sRowColumn.PrimaryMaterialModifierRow, sRowColumn.PrimaryMaterialModifierColumn] = ValueStr; } //Secondary oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.SecondaryDatum; //oRng[sRowColumn.SecondaryDatumRow, sRowColumn.SecondaryDatumColumn] = cTextData.SecondaryDatum; if (cTextData.SecondaryMaterialModifier != "" & cTextData.SecondaryMaterialModifier != "None") { string ValueStr = cTextData.SecondaryMaterialModifier; if (ValueStr == "LeastMaterialCondition") { ValueStr = "l"; } else if (ValueStr == "MaximumMaterialCondition") { ValueStr = "m"; } else if (ValueStr == "RegardlessOfFeatureSize") { ValueStr = "s"; } oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + ValueStr; //oRng[sRowColumn.SecondaryMaterialModifierRow, sRowColumn.SecondaryMaterialModifierColumn] = ValueStr; } //Tertiary oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.TertiaryDatum; //oRng[sRowColumn.TertiaryDatumRow, sRowColumn.TertiaryDatumColumn] = cTextData.TertiaryDatum; if (cTextData.TertiaryMaterialModifier != "" & cTextData.TertiaryMaterialModifier != "None") { string ValueStr = cTextData.TertiaryMaterialModifier; if (ValueStr == "LeastMaterialCondition") { ValueStr = "l"; } else if (ValueStr == "MaximumMaterialCondition") { ValueStr = "m"; } else if (ValueStr == "RegardlessOfFeatureSize") { ValueStr = "s"; } oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + ValueStr; //oRng[sRowColumn.TertiaryMaterialModifierRow, sRowColumn.TertiaryMaterialModifierColumn] = ValueStr; } #endregion } else if (cTextData.Type == "NXOpen.Annotations.Label") { oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = cTextData.MainText; //((Range)oRng[sRowColumn.MainTextRow, sRowColumn.MainTextColumn]).Interior.ColorIndex = 50; } else { #region Dimension填資料 if (cTextData.BeforeText != null) { oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + DefineVariable.GetGDTWord(cTextData.BeforeText); //oRng[sRowColumn.BeforeTextRow, sRowColumn.BeforeTextColumn] = DefineVariable.GetGDTWord(cTextData.BeforeText); } oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + DefineVariable.GetGDTWord(cTextData.MainText); //oRng[sRowColumn.MainTextRow, sRowColumn.MainTextColumn] = DefineVariable.GetGDTWord(cTextData.MainText); //Range a = (Range)oRng[sRowColumn.MainTextRow, sRowColumn.MainTextColumn]; //a.Interior.ColorIndex = 39; if (cTextData.UpperTol != "" & cTextData.TolType == "BilateralOneLine") { oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + "±"; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.UpperTol; string MaxMinStr = "(" + (Convert.ToDouble(cTextData.MainText) + Convert.ToDouble(cTextData.UpperTol)).ToString() + "-" + (Convert.ToDouble(cTextData.MainText) - Convert.ToDouble(cTextData.UpperTol)).ToString() + ")"; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + MaxMinStr; //oRng[sRowColumn.ToleranceSymbolRow, sRowColumn.ToleranceSymbolColumn] = "±"; //oRng[sRowColumn.UpperTolRow, sRowColumn.UpperTolColumn] = cTextData.UpperTol; } else if (cTextData.UpperTol != "" & cTextData.TolType == "BilateralTwoLines") { oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + "+"; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.UpperTol; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + "/"; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.LowerTol; string MaxMinStr = "(" + (Convert.ToDouble(cTextData.MainText) + Convert.ToDouble(cTextData.UpperTol)).ToString() + "-" + (Convert.ToDouble(cTextData.MainText) + Convert.ToDouble(cTextData.LowerTol)).ToString() + ")"; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + MaxMinStr; } else if (cTextData.UpperTol != "" & cTextData.TolType == "UnilateralAbove") { oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + "+"; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.UpperTol; } else if (cTextData.UpperTol != "" & cTextData.TolType == "UnilateralBelow") { //oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + "-"; oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn] = ((Excel.Range)oRng[sRowColumn.DimensionRow, sRowColumn.DimensionColumn]).Value + cTextData.LowerTol; } #endregion } #region 檢具、頻率、Max、Min、泡泡、泡泡位置、料號、日期 oRng[sRowColumn.GaugeRow, sRowColumn.GaugeColumn] = cTextData.Gauge; //oRng[sRowColumn.FrequencyRow, sRowColumn.FrequencyColumn] = cTextData.Frequency; oRng[sRowColumn.BallonRow, sRowColumn.BallonColumn] = cTextData.BallonNum; oRng[sRowColumn.LocationRow, sRowColumn.LocationColumn] = cTextData.Location; oRng[sRowColumn.PartNoRow, sRowColumn.PartNoColumn] = PartNo; oRng[sRowColumn.MaterialRow, sRowColumn.MaterialColumn] = MaterialStr; //oRng[sRowColumn.DateRow, sRowColumn.DateColumn] = CurrentDate; #endregion } book.SaveAs(OutputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); book.Close(Type.Missing, Type.Missing, Type.Missing); x.Quit(); //切回第一張Sheet DefineVariable.FirstDrawingSheet.Open(); UI.GetUI().NXMessageBox.Show("IQC", NXMessageBox.DialogType.Information, "輸出完成"); theProgram.Dispose(); } catch (System.Exception ex) { book.SaveAs(OutputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); book.Close(Type.Missing, Type.Missing, Type.Missing); x.Quit(); } } catch (NXOpen.NXException ex) { // ---- Enter your exception handling code here ----- } return(retValue); }
private void initPose() { init_box.transform.position = listPoses["leftHandForvard"].boxDataPos; init_box.GetComponent <Renderer>().material.SetTexture("_MainTex", listPoses["leftHandForvard"].tex); // root_text = Utility.ShowMessage(TextData.getMessage(userLang, "selAllCol"), "click", TextData.getMessage(userLang, "btnStart"), new Vector2(1200, 200), TextAlignmentOptions.Midline, new Vector2(0, -20), this); root_text = Utility.ShowMessage(listPoses["leftHandForvard"].message, "poseInitReset", TextData.getMessage(userLang, "btn_poseInitReset"), new Vector2(1200, 200), TextAlignmentOptions.Midline, new Vector2(0, -20), this); }
public override IList <TextData> LoadData(System.IO.Stream stream, string path, TextDataCatagory catagoryHint) { //setup a compitent xml reader XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; settings.ValidationType = ValidationType.DTD; settings.MaxCharactersFromEntities = 64 * 1024 * 1024; XmlResolver resolver = GetXMLResolver(); if (resolver != null) { settings.XmlResolver = resolver; } XmlReader reader = XmlReader.Create(stream, settings); XmlDocument xml = new XmlDocument(); xml.Load(reader); List <TextData> items = new List <TextData>(); //do the xml parsing StringBuilder sb = new StringBuilder(); Stack <XmlNode> nodes = new Stack <XmlNode>(); nodes.Push(xml); while (nodes.Count > 0) { XmlNode currentNode = nodes.Pop(); if (useNode(currentNode)) { if (currentNode.Name == "#text") { //Console.Write(indent + node.InnerText); sb.Insert(0, currentNode.InnerText); } else { if (SplitParagraphs && isParagraphNode(currentNode)) { items.Add(TextData.fromParagraph("", sb.ToString(), catagoryHint)); sb.Clear(); } else { string s = nodeToString(currentNode); if (s != null) { sb.Insert(0, s); } } } foreach (XmlNode subNode in currentNode) { nodes.Push(subNode); } } } if (sb.Length > 3) { items.Add(TextData.fromParagraph("", sb.ToString(), catagoryHint)); } //return results return(items); }
// Update is called once per frame void Update() { if (!Active) { return; } else if (Active) { //dialog switch /*if(!contructionButton.activeSelf) * { * * if(closedContructionButton) * { * arrow.localPosition = new Vector3(1.6f, -240.0f, 0.0f); * arrowEasings.ResetEasing(); * closedContructionButton = false; * tutorialDialog.text = TextData.GetText("tutorialDialog2"); * Debug.Log("StartTuto"); * * } * return; * } * tutorialBackground.gameObject.SetActive(true);*/ switch (dialogStates) { case DialogStates.Intro: { tutorialDialog.text = TextData.GetText("tutorialDialog1"); if (advanceTutorial) { advanceTutorial = false; tutorialBackground.gameObject.SetActive(false); arrow.localPosition = new Vector3(-396.0f, -180.0f, 0); arrowEasings.ResetEasing(); tutorialDialog.text = TextData.GetText("tutorialDialog3"); dialogStates = DialogStates.Townhall; } } break; case DialogStates.Construction: { tutorialDialog.text = TextData.GetText("tutorialDialog2"); if (!closedContructionButton) { arrow.localPosition = new Vector3(1.6f, -240.0f, 0.0f); arrowEasings.ResetEasing(); closedContructionButton = false; Debug.Log("Construction"); dialogStates = DialogStates.Start; } } break; case DialogStates.Start: { Debug.Log("start"); tutorialDialog.text = TextData.GetText("tutorialDialog2"); if (advanceTutorial) { advanceTutorial = false; tutorialDialog.text = TextData.GetText("tutorialDialog3"); dialogStates = DialogStates.Townhall; tutorialBackground.gameObject.SetActive(true); } } break; case DialogStates.Townhall: if (resources.townHall >= 1) { arrow.localPosition = new Vector3(houseLock.transform.localPosition.x, houseLock.transform.localPosition.y + 100, houseLock.transform.localPosition.z); arrowEasings.ResetEasing(); houseLock.SetActive(false); actualPos++; building.canCreateBuild = false; dialogStates = DialogStates.House; tutorialDialog.text = TextData.GetText("tutorialDialog4"); } break; case DialogStates.House: if (resources.house >= 3) { arrow.localPosition = new Vector3(farmLock.transform.localPosition.x, farmLock.transform.localPosition.y + 100, farmLock.transform.localPosition.z); arrowEasings.ResetEasing(); houseLock.SetActive(true); farmLock.SetActive(false); actualPos++; building.canCreateBuild = false; dialogStates = DialogStates.Farm; tutorialDialog.text = TextData.GetText("tutorialDialog5"); } if (resources.house == 1 && aura.transform.localPosition == auraPositions[1]) { actualPos++; } if (resources.house == 2 && aura.transform.localPosition == auraPositions[2]) { actualPos++; } break; case DialogStates.Farm: if (resources.farm >= 2) { arrow.localPosition = new Vector3(lumberLock.transform.localPosition.x, lumberLock.transform.localPosition.y + 100, lumberLock.transform.localPosition.z); arrowEasings.ResetEasing(); farmLock.SetActive(true); lumberLock.SetActive(false); actualPos++; building.canCreateBuild = false; dialogStates = DialogStates.Lumber; tutorialDialog.text = TextData.GetText("tutorialDialog6"); } if (resources.farm == 1 && aura.transform.localPosition == auraPositions[4]) { actualPos++; } break; case DialogStates.Lumber: if (resources.lumberMill >= 1) { arrow.localPosition = new Vector3(mineLock.transform.localPosition.x, mineLock.transform.localPosition.y + 100, mineLock.transform.localPosition.z); arrowEasings.ResetEasing(); lumberLock.SetActive(true); mineLock.SetActive(false); actualPos++; building.canCreateBuild = false; dialogStates = DialogStates.Mine; tutorialDialog.text = TextData.GetText("tutorialDialog7"); } break; case DialogStates.Mine: if (resources.goldMine >= 1) { mineLock.SetActive(true); building.canCreateBuild = false; dialogStates = DialogStates.Final; tutorialDialog.text = TextData.GetText("tutorialDialog8"); } break; case DialogStates.Final: houseLock.SetActive(false); farmLock.SetActive(false); lumberLock.SetActive(false); mineLock.SetActive(false); otherLock.SetActive(false); arrow.gameObject.SetActive(false); aura.gameObject.SetActive(false); tutorialBackground.gameObject.SetActive(true); //tutorialDialog.text = TextData.GetText("tutorialDialog9"); if (advanceTutorial) { tutorialBackground.gameObject.SetActive(false); Active = false; gameObject.SetActive(false); } break; default: break; } } aura.transform.localPosition = auraPositions[actualPos]; }
void Awake () { Language.Initialize(); TextData.Initialize(); }
protected abstract List<TextFormatInfo> Parse(TextData textData, Func<bool> isCanceled);
public QuestionDataResponseCategory(TextData data) : base(data) { Type = QuestionDataType.ResponseCategory; Category = (string)data.Values["responseCategory"].Value; }
void ReplaceText(TextLocation start, TextLocation end, TextData replacement, bool moveCaretToEnd) { TextPencil pencil; if (!this.IsReadOnly && this.Buffer.TryGetPencil(out pencil)) { var meta = new SelectionUndoMetadata { OldSelection = GetSelection() }; this.inputBasedEdit = true; using (pencil) { pencil.UndoUnit.Metadata = meta; pencil.Write(start, end, replacement); } this.inputBasedEdit = false; if (moveCaretToEnd) { TextLocation caretLoc; if (replacement.Lines.Count > 1) { caretLoc = new TextLocation(start.Line + replacement.Lines.Count - 1, replacement.Lines[replacement.Lines.Count - 1].Length); } else { caretLoc = new TextLocation(start.Line, start.Index + replacement.Lines[0].Length); } var lineVisual = GetLineVisual(caretLoc.Line); MoveCaret(lineVisual.MapToCoordinate(caretLoc), false); } meta.NewSelection = GetSelection(); } }
TextLocation DetermineNewEnd(TextLocation start, TextLocation end, TextData replacement) { if (replacement.Lines.Count == 1) { // Single-line replacement, meaning the span between start and end (which may be multiple lines) // is being replaced by a single sub-line of text, so the end is on the same line as // the start, past the start index by the length of the inserted sub-line return new TextLocation(start.Line, start.Index + replacement.Lines[0].Length); } // Multi-line replacement, so the end index is always the length of the last line of the replacement. // The end line is simply the start line plus the number of replacement lines (minus one because // the last line of every TextData ends w/ EOB) return new TextLocation(start.Line + replacement.Lines.Count - 1, replacement.Lines[replacement.Lines.Count - 1].Length); }
public SimpleText(TextData data) { textData = data; }
/// <summary> /// On creating the view controller for a specific recordId, the form is checked to see which parameters are required, and the relevant input fields are queued up for adding to the page. /// The relevant data is then extracted from the database for the specific field, and added as the initial value for that field. /// </summary> /// <param name="recId">recordID</param> public FormPageVM(int recId) { using (SQLiteConnection conn = new SQLiteConnection(Preferences.Get("databaseLocation", ""))) { //Get the record and its corresponding variable values var queriedrec = conn.GetWithChildren <Record>(recId); ReadOnly = queriedrec.readOnly; RecId = recId; var txts = queriedrec.texts; var nums = queriedrec.numerics; var bools = queriedrec.booleans; //Compile the GUID BDCGUIDtext = "<<BDC><" + queriedrec.recordId + ">>"; var formId = queriedrec.formId; var formTemp = conn.Table <Form>().Where(Form => Form.formId == formId).FirstOrDefault(); formType = conn.GetWithChildren <Form>(formTemp.Id); foreach (var formField in formType.formFields.OrderBy(f => f.order)) { var label = new Label(); if (formField.title != null && formField.title != String.Empty) { label.Text = formField.title; } else { label.Text = formField.description; } if (formField.mandatory) { label.Text = label.Text + " *"; } label.FontAttributes = FontAttributes.Bold; label.Margin = new Thickness(0, 10, 0, 0); label.SetAppThemeColor(Label.TextColorProperty, Color.Black, Color.White); if (formField.typeId != 31) //Add label next to checkbox for boolean { Assets.Add(label); } if (formField.typeId == 11 || formField.typeId == 61) { try { var text = conn.Table <TextData>().Select(t => t).Where(TextData => TextData.record_fk == RecId).Where(TextData => TextData.formFieldId == formField.fieldId).FirstOrDefault(); var textField = new CustomEntry(); if (text == null) { //CreateNew var txt = new TextData { textId = Guid.NewGuid().ToString(), title = String.Empty, value = String.Empty, formFieldId = formField.fieldId, record_fk = recId }; conn.Insert(txt); txts.Add(txt); queriedrec.texts = txts; conn.UpdateWithChildren(queriedrec); text = txt; } textField = new CustomEntry { Text = text.value.ToString() }; textField.Keyboard = Keyboard.Text; textField.Placeholder = formField.description; textField.ClearButtonVisibility = ClearButtonVisibility.WhileEditing; textField.ReturnType = ReturnType.Done; textField.Margin = new Thickness(0, 0, 0, 10); textField.ValueId = text.Id; textField.TypeId = formField.typeId; textField.TextChanged += TextFieldChanged; textField.IsEnabled = !ReadOnly; textField.Mandatory = formField.mandatory; var empty = String.IsNullOrEmpty(textField.Text); if (formField.mandatory) { Validation.Add((int)textField.ValueId, !empty); } if (ReadOnly) { textField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2)); } Assets.Add(textField); } catch (Exception e) { Console.WriteLine("Could not create field" + e); } } else if (formField.typeId == 41) { try { var text = conn.Table <TextData>().Select(t => t).Where(TextData => TextData.record_fk == RecId).Where(TextData => TextData.formFieldId == formField.fieldId).Take(1).FirstOrDefault(); var dateField = new CustomDatePicker(); var timeField = new CustomTimePicker(); var nowButton = new Button(); var clearButton = new Button(); var stack = new CustomStackLayout() { Orientation = StackOrientation.Horizontal, Children = { dateField, timeField, nowButton, clearButton } }; stack.WidthRequest = 350; stack.HorizontalOptions = LayoutOptions.Start; if (text == null) { //CreateNew var txt = new TextData { textId = Guid.NewGuid().ToString(), title = String.Empty, value = String.Empty, formFieldId = formField.fieldId, record_fk = recId }; conn.Insert(txt); txts.Add(txt); queriedrec.texts = txts; conn.UpdateWithChildren(queriedrec); text = txt; } List <string> choices = Form.FetchFormChoicesForDropdown(formField.fieldId); try { var dt = DateTime.ParseExact(text.value, "yyyy-MM-ddTHH:mm:sszzz", null); if (text.value != null && text.value != String.Empty) { dateField.NullableDate = dt.Date; timeField.NullableDate = new TimeSpan(dt.TimeOfDay.Hours, dt.TimeOfDay.Minutes, 0); } } catch (Exception exp) { Console.WriteLine(exp); } dateField.Margin = new Thickness(0, 0, 0, 10); dateField.ValueId = text.Id; dateField.TypeId = formField.typeId; dateField.Format = "dd MMMM yyyy"; dateField.IsEnabled = !ReadOnly; dateField.WidthRequest = 170; dateField.HeightRequest = 40; dateField.Mandatory = formField.mandatory; dateField.VerticalOptions = LayoutOptions.StartAndExpand; dateField.PropertyChanged += DateFieldChanged; var empty = (dateField.NullableDate == null); if (formField.mandatory) { Validation.Add((int)dateField.ValueId, !empty); } if (ReadOnly) { dateField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2)); } timeField.Margin = new Thickness(0, 0, 0, 0); timeField.ValueId = text.Id; timeField.TypeId = formField.typeId; timeField.Format = "HH:mm"; timeField.IsEnabled = !ReadOnly; timeField.WidthRequest = 70; timeField.HeightRequest = 40; timeField.VerticalOptions = LayoutOptions.StartAndExpand; timeField.Mandatory = formField.mandatory; timeField.PropertyChanged += TimeFieldChanged; if (ReadOnly) { timeField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2)); } Dictionary <String, Object> dic = new Dictionary <string, object>(); dic.Add("text", text); dic.Add("date", dateField); dic.Add("time", timeField); var nowCommand = new Command(FillOutDate); nowButton.Text = "JETZT"; nowButton.TextTransform = TextTransform.Uppercase; nowButton.FontSize = 12; nowButton.Style = (Style)Xamarin.Forms.Application.Current.Resources["TransparentButtonStyle"]; nowButton.Command = nowCommand; nowButton.CommandParameter = dic; nowButton.Margin = new Thickness(10, 0, 0, 0); nowButton.WidthRequest = 40; nowButton.HeightRequest = 40; nowButton.VerticalOptions = LayoutOptions.StartAndExpand; nowButton.IsVisible = !ReadOnly; var clearCommand = new Command(ClearDate); clearButton.Text = "ⓧ"; clearButton.FontSize = 20; clearButton.Style = (Style)Xamarin.Forms.Application.Current.Resources["TransparentButtonStyle"]; clearButton.Command = clearCommand; clearButton.CommandParameter = dic; clearButton.Margin = new Thickness(10, 0, 10, 0); clearButton.WidthRequest = 30; clearButton.HeightRequest = 40; clearButton.VerticalOptions = LayoutOptions.StartAndExpand; clearButton.IsVisible = !ReadOnly; stack.Margin = new Thickness(0, 0, 0, 10); stack.ValueId = text.Id; stack.TypeId = formField.typeId; Assets.Add(stack); } catch (Exception e) { Console.WriteLine("Could not create field" + e); } } else if (formField.typeId == 51) { try { var text = conn.Table <TextData>().Select(t => t).Where(TextData => TextData.record_fk == RecId).Where(TextData => TextData.formFieldId == formField.fieldId).Take(1).FirstOrDefault(); var textField = new CustomPicker(); if (text == null) { //CreateNew var txt = new TextData { textId = Guid.NewGuid().ToString(), title = String.Empty, value = String.Empty, formFieldId = formField.fieldId, record_fk = recId }; conn.Insert(txt); txts.Add(txt); queriedrec.texts = txts; conn.UpdateWithChildren(queriedrec); text = txt; } List <string> choices = Form.FetchFormChoicesForDropdown(formField.Id); textField.ItemsSource = choices; textField.ValueId = text.Id; textField.TypeId = formField.Id; textField.Title = formField.description; textField.IsEnabled = !ReadOnly; textField.Mandatory = formField.mandatory; if (formField.mandatory) { Validation.Add((int)textField.ValueId, textField.SelectedItem != null || (text.value != null && text.value != String.Empty)); } if (ReadOnly) { textField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2)); } textField.SelectedIndexChanged += DidSelectFromChoices; if (text.fieldChoiceId != null) { textField.SelectedIndex = choices.FindIndex(a => a.Contains(text.value)); if (textField.SelectedIndex == -1 && (text.value != null && text.value != String.Empty)) { textField.Title = text.value; } textField.SelectedItem = text.value; } else if (text.value != null && text.value != String.Empty) { textField.Title = text.value; } textField.Margin = new Thickness(0, 0, 0, 10); Assets.Add(textField); } catch (Exception e) { Console.WriteLine("Could not create field" + e); } } else if (formField.typeId == 21) { try { var num = conn.Table <NumericData>().Select(n => n).Where(NumericData => NumericData.record_fk == RecId).Where(NumericData => NumericData.formFieldId == formField.fieldId).Take(1).FirstOrDefault(); var textField = new CustomEntry(); if (num == null) { //CreateNew var nm = new NumericData { numericId = Guid.NewGuid().ToString(), title = String.Empty, value = null, formFieldId = formField.fieldId, record_fk = recId }; conn.Insert(nm); nums.Add(nm); queriedrec.texts = txts; conn.UpdateWithChildren(queriedrec); num = nm; } textField = new CustomEntry { Text = ((double)num.value).ToString("F", CultureInfo.CreateSpecificCulture("de-CH")) }; textField.Keyboard = Keyboard.Numeric; textField.ClearButtonVisibility = ClearButtonVisibility.WhileEditing; textField.ReturnType = ReturnType.Done; textField.Margin = new Thickness(0, 0, 0, 10); textField.ValueId = num.Id; textField.TypeId = formField.typeId; textField.IsEnabled = !ReadOnly; textField.Mandatory = formField.mandatory; var empty = String.IsNullOrEmpty(textField.Text); if (formField.mandatory) { Validation.Add((int)textField.ValueId, !empty); } if (ReadOnly) { textField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2)); } textField.TextChanged += NumericFieldChanged; Assets.Add(textField); } catch (Exception e) { Console.WriteLine("Could not create field" + e); } } else if (formField.typeId == 31) { try { var boolValue = conn.Table <BooleanData>().Select(n => n).Where(BooleanData => BooleanData.record_fk == RecId).Where(BooleanData => BooleanData.formFieldId == formField.fieldId).Take(1).FirstOrDefault(); var checkBox = new CustomCheckBox(); if (boolValue == null) { //CreateNew boolValue = new BooleanData { booleanId = Guid.NewGuid().ToString(), title = String.Empty, value = false, formFieldId = formField.fieldId, record_fk = recId }; conn.Insert(boolValue); bools.Add(boolValue); queriedrec.booleans = bools; conn.UpdateWithChildren(queriedrec); } if (boolValue != null) { checkBox.IsChecked = (bool)boolValue.value; } checkBox.Margin = new Thickness(0, 0, 0, 0); checkBox.ValueId = boolValue.Id; checkBox.TypeId = formField.typeId; checkBox.IsEnabled = !ReadOnly; if (ReadOnly) { checkBox.Color = Color.LightGray; } checkBox.CheckedChanged += BooleanFieldChanged; checkBox.VerticalOptions = LayoutOptions.Fill; checkBox.HorizontalOptions = LayoutOptions.Start; label.VerticalOptions = LayoutOptions.Fill; label.VerticalTextAlignment = TextAlignment.Center; label.Margin = new Thickness(0, 0, 0, 0); var stack = new CustomStackLayout() { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Fill, Children = { checkBox, label } }; stack.Margin = new Thickness(0, 0, 0, 10); Assets.Add(stack); } catch (Exception e) { Console.WriteLine("Could not create field" + e); } } } var geomlabel = new Label(); geomlabel.Text = "Zugeordnete Geometrie"; geomlabel.FontAttributes = FontAttributes.Bold; geomlabel.Margin = new Thickness(0, 10, 0, 0); Assets.Add(geomlabel); AssociatedGeometry = new CustomPicker(); Geoms = ReferenceGeometry.GetAllGeometries().Where(g => g.status < 3).OrderBy(g => g.geometryName).ToList(); foreach (var gm in Geoms) { if (gm.geometryName == null) { gm.geometryName = String.Empty; //Avoid a crash on android from null strings } } var general = new ReferenceGeometry() { geometryName = "Allgemeine Beobachtung" }; AssociatedGeometry.ItemsSource = Geoms; AssociatedGeometry.ItemsSource.Insert(0, general); AssociatedGeometry.ItemDisplayBinding = new Binding("geometryName"); AssociatedGeometry.TypeId = -999; if (queriedrec.geometry_fk != null) { var geom = ReferenceGeometry.GetGeometry((int)queriedrec.geometry_fk); var selectedGeomIndex = Geoms.FindIndex(a => a.Id == geom.Id); AssociatedGeometry.SelectedIndex = selectedGeomIndex++; } else { AssociatedGeometry.SelectedIndex = 0; } AssociatedGeometry.Margin = new Thickness(0, 0, 0, 10); AssociatedGeometry.IsEnabled = !ReadOnly; if (ReadOnly) { AssociatedGeometry.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2)); } AssociatedGeometry.SelectedIndexChanged += DidSelectNewGeometry; Assets.Add(AssociatedGeometry); } var DeleteButton = new Button(); DeleteCommand = new Command(OnDelete, ValidateDelete); DeleteButton.ImageSource = "delete.png"; DeleteButton.Command = DeleteCommand; DeleteButton.Style = (Style)Xamarin.Forms.Application.Current.Resources["DangerButtonStyle"]; DeleteButton.Margin = new Thickness(0, 10); DeleteButton.CornerRadius = 10; DeleteButton.TextTransform = TextTransform.Uppercase; DeleteButton.WidthRequest = 50; var GUIDButton = new Button(); GUIDCommand = new Command(CopyGUID); GUIDButton.Text = "GUID"; GUIDButton.BackgroundColor = (Color)Xamarin.Forms.Application.Current.Resources["BioDivGreen"]; GUIDButton.Command = GUIDCommand; GUIDButton.HorizontalOptions = LayoutOptions.FillAndExpand; GUIDButton.TextColor = Color.White; GUIDButton.Margin = new Thickness(0, 10); GUIDButton.CornerRadius = 10; GUIDButton.TextTransform = TextTransform.Uppercase; GUIDButton.WidthRequest = 250; var buttonLayout = new FlexLayout { Children = { DeleteButton, GUIDButton } }; buttonLayout.Direction = FlexDirection.Row; buttonLayout.JustifyContent = FlexJustify.SpaceAround; buttonLayout.HorizontalOptions = LayoutOptions.FillAndExpand; buttonLayout.AlignContent = FlexAlignContent.SpaceAround; Assets.Add(buttonLayout); SaveCommand = new Command(OnSave, ValidateSave); CancelCommand = new Command(OnCancel); this.PropertyChanged += (_, __) => SaveCommand.ChangeCanExecute(); }
private void DrawDivisions(double scrollOffset, AnyChart parent, Transform parentTransform, ChartDivisionInfo info, IChartMesh mesh, int group, ChartOrientation orientation, double gap, bool oppositeSide, double mainGap) { //scrollOffset = -scrollOffset; double parentSize = (orientation == ChartOrientation.Vertical) ? ((IInternalUse)parent).InternalTotalHeight : ((IInternalUse)parent).InternalTotalWidth; DoubleVector3 startPosition, lengthDirection, advanceDirection; GetDirectionVectors(parent, info, orientation, 0f, oppositeSide, out startPosition, out lengthDirection, out advanceDirection); double markDepth = ChartCommon.GetAutoDepth(parent, orientation, info); double length = ChartCommon.GetAutoLength(parent, orientation, info); double backLength = (orientation == ChartOrientation.Vertical) ? ((IInternalUse)parent).InternalTotalWidth : ((IInternalUse)parent).InternalTotalHeight; if (info.MarkBackLength.Automatic == false) { backLength = info.MarkBackLength.Value; } double totaluv = Math.Abs(length); if (backLength != 0 && markDepth > 0) { totaluv += Math.Abs(backLength) + Math.Abs(markDepth); } DoubleVector3 halfThickness = advanceDirection * (info.MarkThickness * 0.5f); // if (scrollOffset != 0f) // last--; bool hasValues = ((IInternalUse)parent).InternalHasValues(this); double maxValue = ((IInternalUse)parent).InternalMaxValue(this); double minValue = ((IInternalUse)parent).InternalMinValue(this); double range = maxValue - minValue; float AutoAxisDepth = Depth.Value; // float scrollFactor = (scrollOffset / (float)(maxValue - minValue)); //scrollOffset = scrollFactor * parentSize; if (Depth.Automatic) { AutoAxisDepth = (float)((((IInternalUse)parent).InternalTotalDepth) - markDepth); } double startValue = (scrollOffset + minValue); double endValue = (scrollOffset + maxValue) + double.Epsilon; Func <double, double> ValueToPosition = x => ((x - startValue) / range) * parentSize; double fraction = gap - (scrollOffset - Math.Floor((scrollOffset / gap) - double.Epsilon) * gap); double mainfraction = -1f; double currentMain = 0f; if (mainGap > 0f) { mainfraction = mainGap - (scrollOffset - Math.Floor((scrollOffset / mainGap) - double.Epsilon) * mainGap); currentMain = (scrollOffset + minValue + mainfraction); } int i = 0; mTmpToRemove.Clear(); double startRange = startValue + fraction; foreach (double key in mFormats.Keys) { if (key > endValue || key < startRange) { mTmpToRemove.Add(key); } } for (int k = 0; k < mTmpToRemove.Count; k++) { mFormats.Remove(mTmpToRemove[k]); } for (double current = startRange; current <= endValue; current += gap) { ++i; if (i > 3000) { break; } if (mainGap > 0.0) { if (Math.Abs(current - currentMain) < 0.00001) { currentMain += mainGap; continue; } if (current > currentMain) { currentMain += mainGap; } } double offset = ValueToPosition(current); DoubleVector3 start = startPosition + advanceDirection * offset; DoubleVector3 size = halfThickness + length * lengthDirection; start -= halfThickness; //size += halfThickness; float uvoffset = 0f; Rect r = ChartCommon.FixRect(new Rect((float)start.x, (float)start.y, (float)size.x, (float)size.y)); SetMeshUv(mesh, (float)(-length / totaluv), uvoffset); uvoffset += Math.Abs(mesh.Length); mesh.AddXYRect(r, group, AutoAxisDepth); if (hasValues) { double val = Math.Round(current * 1000.0) / 1000.0; string toSet = ""; double keyVal = val;// (int)Math.Round(val); var dic = (orientation == ChartOrientation.Horizontal) ? parent.HorizontalValueToStringMap : parent.VerticalValueToStringMap; if (!(Math.Abs(val - keyVal) < 0.001 && dic.TryGetValue(keyVal, out toSet))) { if (mFormats.TryGetValue(val, out toSet) == false) { if (format == AxisFormat.Number) { toSet = ChartAdancedSettings.Instance.FormatFractionDigits(info.FractionDigits, val); } else { DateTime date = ChartDateUtility.ValueToDate(val); if (format == AxisFormat.DateTime) { toSet = ChartDateUtility.DateToDateTimeString(date, parent.CustomDateTimeFormat); } else { if (format == AxisFormat.Date) { toSet = ChartDateUtility.DateToDateString(date); } else { toSet = ChartDateUtility.DateToTimeString(date); } } } toSet = info.TextPrefix + toSet + info.TextSuffix; mFormats[val] = toSet; } } else { toSet = info.TextPrefix + toSet + info.TextSuffix; } DoubleVector3 textPos = new DoubleVector3(start.x, start.y); textPos += lengthDirection * info.TextSeperation; TextData userData = new TextData(); userData.interp = (float)(offset / parentSize); userData.info = info; userData.fractionDigits = info.FractionDigits; mesh.AddText(parent, info.TextPrefab, parentTransform, info.FontSize, info.FontSharpness, toSet, (float)textPos.x, (float)textPos.y, AutoAxisDepth + info.TextDepth, 0f, userData); } if (markDepth > 0) { if (orientation == ChartOrientation.Horizontal) { SetMeshUv(mesh, (float)(markDepth / totaluv), uvoffset); r = ChartCommon.FixRect(new Rect((float)start.x, AutoAxisDepth, (float)size.x, (float)markDepth)); mesh.AddXZRect(r, group, (float)start.y); } else { SetMeshUv(mesh, (float)(-markDepth / totaluv), uvoffset); r = ChartCommon.FixRect(new Rect((float)start.y, AutoAxisDepth, (float)size.y, (float)markDepth)); mesh.AddYZRect(r, group, (float)start.x); } uvoffset += Math.Abs(mesh.Length); if (backLength != 0) { SetMeshUv(mesh, (float)(backLength / totaluv), uvoffset); uvoffset += Math.Abs(mesh.Length); DoubleVector3 backSize = halfThickness + backLength * lengthDirection; Rect backR = ChartCommon.FixRect(new Rect((float)start.x, (float)start.y, (float)backSize.x, (float)backSize.y)); mesh.AddXYRect(backR, group, (float)(AutoAxisDepth + markDepth)); } } } // Debug.Log("start"); // Debug.Log(mFormats.Count); // Debug.Log(cached); }
static void Main(string[] args) { var argList = args.Select(o => o.Trim()); ValidateArgs(argList); var argHash = new TextData(argList.Skip(1).Join(string.Empty), '/', 1); var action = args[0]; var path = Arg(argHash, 'p', Assembly.GetEntryAssembly().Location); var target = Arg(argHash, 't', string.Empty); Initializer.Initialize( path, assemblyVersion: Assembly.GetExecutingAssembly().GetName().Version.ToString(), codeDefiner: true, setSaPassword: argHash.ContainsKey("s"), setRandomPassword: argHash.ContainsKey("r")); Performances.Record(MethodBase.GetCurrentMethod().Name); DeleteTemporaryFiles(); switch (action) { case "_rds": ConfigureDatabase(); break; case "rds": ConfigureDatabase(); CreateDefinitionAccessorCode(); CreateMvcCode(target); break; case "_def": CreateDefinitionAccessorCode(); break; case "def": CreateDefinitionAccessorCode(); CreateMvcCode(target); break; case "mvc": CreateMvcCode(target); break; case "css": CreateCssCode(); break; case "backup": CreateSolutionBackup(); break; case "insert_testdata": InsertTestData(); break; default: WriteErrorToConsole(args); break; } Performances.Record(MethodBase.GetCurrentMethod().Name); Performances.PerformanceCollection.Save(Directories.Logs()); Consoles.Write( DisplayAccessor.Displays.Get("CodeDefinerCompleted"), Consoles.Types.Success); WaitConsole(args); }
/// <summary> /// Add text at 3D position. /// </summary> /// <param name="worldPos">3D world-space position for text</param> /// <param name="text">Text to draw</param> /// <param name="color">Color of text</param> public void AddText(Vector3 worldPos, String text, Justify justify, Color color) { if (sTextList.Count >= MAX_TEXT_LINES) { return; } TextData textData = new TextData(); textData.mPos = worldPos; textData.mText = text; textData.mColor = color; textData.mJustify = justify; textData.mIsTransformed = false; sTextList.Add(textData); }
//------------------------------------------------------------------------------- /// <summary> /// テキストをセットします。指定回数表示された後は表示されません。 /// </summary> /// <param name="text">テキスト</param> /// <param name="times">表示回数, 0以下を指定すると無限</param> public void SetText(string text, int times) { TextData data = new TextData() { type = (times > 0) ? TextDataType.Some_Times : TextDataType.Permanent, restNum = times }; lock (_objSync) { _firstQueue.Enqueue(text); if (_textDic.ContainsKey(text)) { _textDic.Remove(text); } else { _textDic.Add(text, data); } StartThreadIfNotActive(); } }