static void Main() { var configPath = @"D:\Projects\cs\lab4\ServiceLayer\ServiceConfig.json"; var configProvider = new ConfigProvider(configPath); var serviceModel = configProvider.GetConfig <ServiceModel>(); var connectionString = serviceModel.ConnectionString; var targetPath = serviceModel.TargetXmlPath; var errorLogger = new Logger(); int id = 5; try { PersonalInfo personalInfo = new PersonalInfo();//////// personalInfo.Name = "testName"; personalInfo.PhoneNumber = "testPhone"; LoginInfo loginInfo = new LoginInfo(connectionString, id); AddressInfo addressInfo = new AddressInfo();/////// addressInfo.Address = "testAddress"; XmlModel obj = new XmlModel(personalInfo, loginInfo, addressInfo); XmlCreator creator = new XmlCreator(); creator.CreateXmlFile(obj, targetPath); } catch (Exception e) { errorLogger.AddError(e, DateTime.Now); } }
private static GleeGraph CreateAndLayoutGraph(XmlModel xmlParser) { startNode = xmlParser.StartState; var graph = new GleeGraph { Margins = margin }; foreach (var state in xmlParser.States) { graph.AddNode(new Node(state, new Ellipse(nodeWidth, nodeHeight, new P()))); } foreach (var transition in xmlParser.Transitions) { var e = new Edge(graph.NodeMap[transition.From], graph.NodeMap[transition.To]) { UserData = transition.Trigger }; graph.AddEdge(e); } graph.CalculateLayout(); return(graph); }
public void CreateXmlFile(XmlModel obj, string targetPath) { XmlSerializer serializer = new XmlSerializer(typeof(XmlModel)); using (var fs = new FileStream(targetPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { serializer.Serialize(fs, obj); } XmlReader reader = XmlReader.Create(targetPath); XmlSchemaSet schemaSet = new XmlSchemaSet(); XmlSchemaInference schema = new XmlSchemaInference(); schemaSet = schema.InferSchema(reader); targetPath = Path.ChangeExtension(targetPath, ".xsd"); foreach (XmlSchema s in schemaSet.Schemas()) { using (var sw = new StringWriter()) { using (var writer = XmlWriter.Create(sw)) { s.Write(writer); } File.WriteAllText(targetPath, sw.ToString()); } } }
public void ImportProposalsFromXml(XmlModel model) { if (!_urh.IsEditor(UmbracoContext.Security.GetUserId())) { return; } IEnumerable <ExportedTranslationTask> proposals = ReadXml(model); // Nothing to process. if (!proposals.Any()) { return; } List <TranslationProposal> data = new List <TranslationProposal>(); var userId = UmbracoContext.Security.GetUserId(); foreach (var p in proposals) { data.Add(new TranslationProposal { LanguageId = p.LanguageId, UniqueId = p.UniqueId, UserId = userId, Timestamp = DateTime.UtcNow, Value = p.TranslatedText }); } if (data.Any()) { _db.BulkInsertRecords(data); } }
public static void CustomSubMenu1() { OpenFileDlg pth = new OpenFileDlg(); pth.structSize = System.Runtime.InteropServices.Marshal.SizeOf(pth); pth.filter = "支持的模型文件(*.3DXML)\0*.3DXML"; pth.file = new string(new char[256]); pth.maxFile = pth.file.Length; pth.fileTitle = new string(new char[64]); pth.maxFileTitle = pth.fileTitle.Length; pth.initialDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // default path pth.title = "导入模型"; pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008; if (!OpenFileDialog.GetOpenFileName(pth)) { return; } string filepath = pth.file; //选择的文件路径; //Debug.Log(filepath); XmlModel x = new XmlModel(filepath); DestroyImmediate(GameObject.Find("ModelGenerator")); x.Render(new GameObject("ModelGenerator")); //打出一行字:模板生成在。。。.xml,请手动设置动画参数,或使用第二个选项自动设置参数。 }
public ViewModel(XmlStore xmlStore, XmlModel xmlModel, IServiceProvider provider, IVsTextLines buffer) { if (xmlModel == null) throw new ArgumentNullException("xmlModel"); if (xmlStore == null) throw new ArgumentNullException("xmlStore"); if (provider == null) throw new ArgumentNullException("provider"); if (buffer == null) throw new ArgumentNullException("buffer"); this.BufferDirty = false; this.DesignerDirty = false; this._serviceProvider = provider; this._buffer = buffer; this._xmlStore = xmlStore; // OnUnderlyingEditCompleted _editingScopeCompletedHandler = new EventHandler<XmlEditingScopeEventArgs>(OnUnderlyingEditCompleted); this._xmlStore.EditingScopeCompleted += _editingScopeCompletedHandler; // OnUndoRedoCompleted _undoRedoCompletedHandler = new EventHandler<XmlEditingScopeEventArgs>(OnUndoRedoCompleted); this._xmlStore.UndoRedoCompleted += _undoRedoCompletedHandler; this._xmlModel = xmlModel; // BufferReloaded _bufferReloadedHandler += new EventHandler(BufferReloaded); this._xmlModel.BufferReloaded += _bufferReloadedHandler; LoadModelFromXmlModel(); }
public void ImportTranslationsFromXml(XmlModel model) { if (!_urh.IsEditor(UmbracoContext.Security.GetUserId())) { return; } IEnumerable <ExportedTranslationTask> translations = ReadXml(model); // Nothing to process. if (!translations.Any()) { return; } var keys = translations.Select(x => x.UniqueId); var languageId = translations.First().LanguageId; var existingTranslations = _db.Fetch <TranslationText>("select * from dbo.cmsLanguageText where UniqueId IN (@tags1) AND languageId=@tag2", new { tags1 = keys, tag2 = languageId }).ToDictionary(x => x.UniqueId, x => x); var newKeys = translations.Where(x => !existingTranslations.ContainsKey(x.UniqueId)).Select(x => new TranslationText { LanguageId = languageId, UniqueId = x.UniqueId, Value = x.TranslatedText }); if (newKeys.Any()) { _db.BulkInsertRecords(newKeys); } foreach (var translation in translations) { TranslationText existingTranslation; if (!existingTranslations.TryGetValue(translation.UniqueId, out existingTranslation)) { continue; } existingTranslation.Value = translation.TranslatedText; _db.Update(existingTranslation); } _db.Delete <TranslationProposal>(new Sql().Where("id IN (@tags1) AND languageId=@tag2", new { tags1 = keys, tag2 = languageId })); _db.Delete <TranslationTask>(new Sql().Where("id IN (@tags1) AND languageId=@tag2", new { tags1 = keys, tag2 = languageId })); }
private void RefreshEditor() { XmlEditorService es = GetService(typeof(XmlEditorService)) as XmlEditorService; _store = es.CreateXmlStore(); _store.UndoManager = _undoManager; _model = _store.OpenXmlModel(new Uri(_fileName)); _textBuffer.Reload(1); if (ManifestEditorFactory.ExcuteToCheckXmlRule(_fileName)) { _ManifestDesignerControl.IsEnabled = true; try { _ManifestDesignerControl.Refresh(new ViewModelTizen(_store, _model, this, _textBuffer)); var vsRunningDocumentTable = GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; var hr = vsRunningDocumentTable.NotifyDocumentChanged(_documentCookie, (uint)__VSRDTATTRIB.RDTA_DocDataReloaded); ErrorHandler.ThrowOnFailure(hr); } catch { } } else { _ManifestDesignerControl.IsEnabled = false; } }
private static void SaveToFile(XmlModel item) { var xs = new XmlSerializer(typeof(XmlModel)); using (StreamWriter wr = new StreamWriter(Filename)) { xs.Serialize(wr, item); } }
public void TestXmlDeserialize() { XmlSerial serial = new XmlSerial(); XmlModel model = serial.DeserializeDataFromFile(); Assert.AreEqual(model.Name, serial.GetModel().Name); Assert.AreEqual(model.Id, serial.GetModel().Id); }
public static void ResetSettings() { var model = new XmlModel(); model.Categories = buildSampleCategories(); SaveToFile(model); }
public static XmlModel LoadXml(string path) { XmlSerializer reader = new XmlSerializer(typeof(XmlModel)); StreamReader file = new StreamReader(path); XmlModel overview = (XmlModel)reader.Deserialize(file); file.Close(); return(overview); }
public List <XmlModel> LoadData() { List <XmlModel> datas = new List <XmlModel>(); XmlDocument xDoc = new XmlDocument(); xDoc.Load(pathToXml); XmlElement xRoot = xDoc.DocumentElement; foreach (XmlNode xnode in xRoot) { //получаем data XmlModel data = new XmlModel(); data.Notes = new List <NoteModel>(); data.Spendings = new List <SpendingModel>(); // получаем атрибут date if (xnode.Attributes.Count > 0) { XmlNode attr = xnode.Attributes.GetNamedItem("date"); if (attr != null) { data.Date = DateTime.Parse(attr.Value); } } // обходим все дочерние узлы элемента spendings foreach (XmlNode childnode in xnode.ChildNodes) { if (childnode.Name == "spending") { SpendingModel spending = new SpendingModel(); foreach (XmlNode child in childnode.ChildNodes) { if (child.Name == "amount") { spending.Message = child.Value; } if (child.Name == "message") { spending.Message = child.Value; } } data.Spendings.Add(spending); } else { NoteModel note = new NoteModel(); foreach (XmlNode child in childnode.ChildNodes) { note.Message = child.Value; } data.Notes.Add(note); } } datas.Add(data); } return(datas); }
public void RunIntegratedTest() { XmlModel model = parser.parseXmlFile("../../../DemoFiles/SampleData.xml"); Assert.AreEqual(3, model.Nodes.Count); validateCustInfoNode(model.Nodes[0]); validateTelecomServicesSummary(model.Nodes[1]); validateCallsNode(model.Nodes[2]); }
public static void Validate(XmlModel.PropertyDeserializer property) { if (!Regex.IsMatch(property.AgencyCode, "[a-zA-Z0-9!@#$%^&*()_+ ]*")) throw new ArgumentException("Agency Code Not Valid"); if (!Regex.IsMatch(property.Name, "[a-zA-Z0-9!@#$%^&*()_+ ]*")) throw new ArgumentException("Name Not Valid"); if (!Regex.IsMatch(property.Address, "[a-zA-Z0-9!@#$%^&*()_+ ]*")) throw new ArgumentException("Address Not Valid"); }
public void SaveData(XmlModel data) { if (!File.Exists(pathToXml)) { XmlTextWriter textWritter = new XmlTextWriter(pathToXml, Encoding.UTF8); textWritter.WriteStartDocument(); textWritter.WriteStartElement("head"); textWritter.WriteEndElement(); textWritter.Close(); } CreateDocument(data).Save(pathToXml); }
public static Transactions ToTransaction(this XmlModel xmlModel) { var transactionHistory = new Transactions { TransactionId = xmlModel.Id }; DateTime.TryParse(xmlModel.TransactionDate, out var dateTime); transactionHistory.TransactionDate = dateTime; decimal.TryParse(xmlModel.PaymentDetails.Amount, out var amount); transactionHistory.Amount = amount; transactionHistory.CurrencyCode = xmlModel.PaymentDetails.CurrencyCode; transactionHistory.Status = xmlModel.Status; return(transactionHistory); }
public ActionResult XmlAction() { XmlModel obj = new XmlModel { Name = "Hello", Child = new XmlChildModel { ChildName = "World" } }; return(this.Xml(obj)); // Extension //return new XmlResult( ); }
private bool SendAnnotationsToGrid(List <aim_dotnet.Annotation> annotations) { if (annotations == null || annotations.Count == 0) { return(true); } var xmlAnnotations = new Dictionary <string, string>(); var xmlModel = new XmlModel(); foreach (var annotation in annotations) { try { xmlAnnotations.Add(annotation.UniqueIdentifier, xmlModel.WriteAnnotationToXmlString(annotation)); } catch (Exception ex) { Platform.Log(LogLevel.Error, ex, "Failed to convert annotation to xml."); } } xmlModel = null; // Send Annotations to AIM Service if (xmlAnnotations.Count > 0) { BackgroundTask task = null; try { task = new BackgroundTask(BackgroundSendAnnotationsToAimService, false, xmlAnnotations); ProgressDialog.Show(task, DesktopWindow, true); return(true); } catch (Exception e) { Platform.Log(LogLevel.Error, e, "Failed to send annotation(s) to the AIM data service"); DesktopWindow.ShowMessageBox("Failed to send annotation(s) to the AIM data service. See log for details.", MessageBoxActions.Ok); } finally { if (task != null) { task.Dispose(); } } } return(false); }
/// <summary> /// Constructor /// </summary> /// <param name="xmlStore">THe XML Store</param> /// <param name="xmlModel">The XML Model</param> /// <param name="provider">The Service Provider</param> /// <param name="buffer">The buffer</param> public ViewModel(XmlStore xmlStore, XmlModel xmlModel, IServiceProvider provider, IVsTextLines buffer, string fileName, XmlModel defaultTables) { if (defaultTables == null) { throw new ArgumentNullException("defaultTables"); } if (xmlModel == null) { throw new ArgumentNullException("xmlModel"); } if (xmlStore == null) { throw new ArgumentNullException("xmlStore"); } if (provider == null) { throw new ArgumentNullException("provider"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } BufferDirty = false; DesignerDirty = false; ServiceProvider = provider; _buffer = buffer; _xmlStore = xmlStore; // OnUnderlyingEditCompleted _editingScopeCompletedHandler = new EventHandler <XmlEditingScopeEventArgs>(OnUnderlyingEditCompleted); _xmlStore.EditingScopeCompleted += _editingScopeCompletedHandler; // OnUndoRedoCompleted _undoRedoCompletedHandler = new EventHandler <XmlEditingScopeEventArgs>(OnUndoRedoCompleted); _xmlStore.UndoRedoCompleted += _undoRedoCompletedHandler; _defaultTables = defaultTables; _xmlModel = xmlModel; // BufferReloaded _bufferReloadedHandler += new EventHandler(BufferReloaded); _xmlModel.BufferReloaded += _bufferReloadedHandler; m_FileName = fileName; LoadModelFromXmlModel(); }
public static Bitmap ConvertModelToBitmap(XmlModel model) { try { var graph = CreateAndLayoutGraph(model); var bitmap = new Bitmap((int)graph.BoundingBox.Width, (int)graph.BoundingBox.Height); DrawGraph(bitmap, graph); return(bitmap); } catch (Exception) { var thisAssembly = System.Reflection.Assembly.GetExecutingAssembly(); var file = thisAssembly.GetManifestResourceStream("StatelessGraph.Resources.Error.png"); return(new Bitmap(Image.FromStream(file))); } }
private void AddNewCardFromCsv(IList newCsvItems) { if (newCsvItems != null) { CsvModel csvClient = (CsvModel)(newCsvItems[0]); XmlModel matchedXmlClient = _xmlModels.FirstOrDefault(el => el.ClientId == csvClient.ClientId); if (matchedXmlClient.ClientId != null && _cardModels.All(el => el.ClientId != csvClient.ClientId)) { Card card = new Card(matchedXmlClient.ClientId, matchedXmlClient.Pan, csvClient.FName, csvClient.LName, csvClient.Telephone, matchedXmlClient.Date); _cardModels.Add(card); } } }
public static string IsValid(this XmlModel xmlModel, int index, string uploadedFileName) { var invalidItems = new List <string>(); var paymentDetails = new List <string> { CommonConstant.Amount, CommonConstant.CurrencyCode }; if (string.IsNullOrWhiteSpace(xmlModel.Id)) { invalidItems.Add(CommonConstant.TransactionId); } if (string.IsNullOrWhiteSpace(xmlModel.TransactionDate) || !DateTime.TryParse(xmlModel.TransactionDate, out var transactionDate)) { invalidItems.Add(CommonConstant.TransactionDate); } if (string.IsNullOrWhiteSpace(xmlModel.Status)) { invalidItems.Add(CommonConstant.Status); } if (xmlModel.PaymentDetails == null) { invalidItems.AddRange(paymentDetails); } else if (string.IsNullOrWhiteSpace(xmlModel.PaymentDetails.Amount) || !decimal.TryParse(xmlModel.PaymentDetails.Amount, out var amount)) { invalidItems.Add(paymentDetails[0]); } else if (string.IsNullOrWhiteSpace(xmlModel.PaymentDetails.CurrencyCode)) { invalidItems.Add(paymentDetails[1]); } if (!invalidItems.Any()) { return(string.Empty); } var errorMsg = $"In File: {uploadedFileName}, Transaction #{index}, {CommonConstant.InvalidItems}" + string.Join(", ", invalidItems); return(errorMsg); }
/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { RegisterIndependentView(false); using (_model) { _model = null; } using (_store) { _store = null; } } base.Dispose(disposing); }
private void AddCardFromNewXml(IList xmlItems) { if (xmlItems != null) { XmlModel newXmlClient = (XmlModel)(xmlItems[0]); CsvModel matchedCsvClient = _csvModels.FirstOrDefault(el => el.ClientId == newXmlClient.ClientId); bool alreadyExists = _cardModels.All(el => el.ClientId == newXmlClient.ClientId); if (matchedCsvClient.ClientId != null && !alreadyExists) { Card card = new Card(newXmlClient.ClientId, newXmlClient.Pan, matchedCsvClient.FName , matchedCsvClient.LName, matchedCsvClient.Telephone, newXmlClient.Date); _cardModels.Add(card); } } }
public static Transaction ToTransaction(this XmlModel xmlModel) { Transaction transactionDto = new Transaction { TransactionId = xmlModel.Id }; DateTime.TryParse(xmlModel.TransactionDate, out var dateTime); transactionDto.TransactionDate = dateTime; decimal.TryParse(xmlModel.PaymentDetails.Amount, out var amount); transactionDto.Amount = amount; transactionDto.CurrencyCode = xmlModel.PaymentDetails.CurrencyCode; transactionDto.Status = xmlModel.Status; return(transactionDto); }
private List <XmlModel> modelxml(XDocument xdocument) { List <XmlModel> attendeesmodel = new List <XmlModel>(); var loaddata = (from s in xdocument.Descendants("Content").Elements() select new { ImportId = s.Element("TextField.Importid").Attribute("Text").Value, Firstname = s.Element("TextField.Firstname").Attribute("Text").Value, Lastname = s.Element("TextField.Lastname").Attribute("Text").Value, Companyname = s.Element("TextField.Companyname").Attribute("Text").Value, Title = s.Element("TextField.Title").Attribute("Text").Value, Mailcity = s.Element("TextField.Mailcity").Attribute("Text").Value, Mailstate = s.Element("TextField.Mailstate").Attribute("Text").Value, Phone = s.Element("TextField.Phone").Attribute("Text").Value, Email = s.Element("TextField.Email").Attribute("Text").Value, Webpage = s.Element("TextField.Webpage").Attribute("Text").Value, Spouse = s.Element("TextField.Spouse").Attribute("Text").Value, Guest = s.Element("TextField.Guest").Attribute("Text").Value, Firsttime = s.Element("TextField.Firsttime").Attribute("Text").Value }).ToList(); foreach (var id in loaddata) { XmlModel obj = new XmlModel(); obj.ImportId = id.ImportId; obj.Firstname = id.Firstname; obj.Lastname = id.Lastname; obj.Companyname = id.Companyname; obj.Title = id.Title; obj.Mailcity = id.Mailcity; obj.Mailstate = id.Mailstate; obj.Phone = id.Phone; obj.Email = id.Email; obj.Webpage = id.Webpage; obj.ImportId = id.ImportId; obj.Spouse = id.Spouse; obj.Guest = id.Guest; obj.Firsttime = id.Firsttime; attendeesmodel.Add(obj); } return(attendeesmodel); }
public Form1() { InitializeComponent(); var providerName = ConfigurationManager.AppSettings["ProviderName"].ToString(); var providerNameList = providerName.Split('|').ToList(); providerNameList.ForEach(p => { cbxProviderName.Items.Add(p); }); XmlModel model = XmlHelper.Get(); txtConnectionString.Text = model.ConnectionString; cbxProviderName.Text = model.ProviderName; }
public Result PostXml(XmlModel inObj) { var reObj = new Result(); //表示是有推广人的订阅 if (inObj.Event.Equals("subscribe") && !string.IsNullOrEmpty(inObj.Ticket) && !string.IsNullOrEmpty(inObj.FromUserName)) { // var saveEnt= new EtcWeixinEntity() // { // openid = inObj.FromUserName, // createTime = DateTime.Now, // parentTicket = inObj.Ticket, // eventKey = inObj.EventKey, // }; // return await weixin.save(saveEnt); } return(reObj); }
/// <summary> /// Get an up to date XML parse tree from the XML Editor. /// </summary> XDocument GetParseTree(XmlModel model) { LanguageService langsvc = GetXmlLanguageService(); // don't crash if the language service is not available if (langsvc != null) { Source src = langsvc.GetSource(_buffer); // We need to access this method to get the most up to date parse tree. // public virtual XmlDocument GetParseTree(Source source, IVsTextView view, int line, int col, ParseReason reason) { MethodInfo mi = langsvc.GetType().GetMethod("GetParseTree"); int line = 0, col = 0; mi.Invoke(langsvc, new object[] { src, null, line, col, ParseReason.Check }); } // Now the XmlDocument should be up to date also. return(model.Document); }
public static XmlModel Transform(List <DB.Model.Source> sources, List <DB.Model.Sensor> sensors, List <DB.Model.Parameter> parameters, List <Value> values) { XmlModel xml = new XmlModel { MeasuredValues = new List <MeasuredValue>() }; values.ForEach(delegate(Value value) { var parameterDb = parameters.Where(parameter => parameter.ParameterUuid.Equals(value.ParameterId)).FirstOrDefault(); var sensorDb = sensors.Where(sensor => sensor.SensorUuid.Equals(parameterDb.SensorId)).FirstOrDefault(); var sourceDb = sources.Where(source => source.SourceUuid.Equals(sensorDb.SourceId)).FirstOrDefault(); xml.MeasuredValues.Add(new MeasuredValue() .WithUUID(value.ValueUuid) .WithTimeStampStart(value.TimestampStart.ToString()) .WithTimeStampEnd(value.TimestampEnd.ToString()) .WithValue(value.ValueField) .WithParameter(new Model.Parameter() .WithUUID(parameterDb.ParameterUuid) .WithCode(parameterDb.Code) .WithUnit(parameterDb.Unit) .WithType(parameterDb.Type) .WithSensor(new Model.Sensor() .WithUUID(sensorDb.SensorUuid) .WithState(sensorDb.State) .WithSource(new Model.Source() .WithUUID(sourceDb.SourceUuid) .WithPNIV(sourceDb.Pniv) ) ) .WithDescription(parameterDb.Description) ) ); }); return(xml); }
private IEnumerable <ExportedTranslationTask> ReadXml(XmlModel model) { ExportedTranslationTask[] proposals; using (var s = new StringReader(model.Value)) { var xs = new XmlSerializer(typeof(ExportedTranslationTask[])); proposals = (ExportedTranslationTask[])xs.Deserialize(s); } var languages = proposals.Select(x => x.LanguageId).Distinct(); // The feature expects the xml file to contain keys for a single language, as it makes sense in practice. if (languages.Count() > 1) { throw new HttpException("Invalid xml file. Expected file with single language."); } var languageExists = _db.Fetch <int>("select 1 from dbo.umbracoLanguage where id=@tag", new { tag = languages.First() }).Any(); if (!languageExists) { throw new HttpException("Invalid xml file. File contains invalid language."); } var validKeys = _db.Fetch <int>("select 1 from dbo.cmsDictionary where id IN (@tags)", new { tags = proposals.Select(x => x.UniqueId).Distinct() }); if (validKeys.Count != proposals.Length) { throw new HttpException("Invalid xml file. File contains non existing keys."); } // We dont want empty texts. return(proposals.Where(x => !string.IsNullOrWhiteSpace(x.TranslatedText))); }
/// <summary> /// Called after the WindowPane has been sited with an IServiceProvider from the environment /// protected override void Initialize() { base.Initialize(); // Create and initialize the editor #region Register with IOleComponentManager IOleComponentManager componentManager = (IOleComponentManager)GetService(typeof(SOleComponentManager)); if (this._componentId == 0 && componentManager != null) { OLECRINFO[] crinfo = new OLECRINFO[1]; crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)); crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime | (uint)_OLECRF.olecrfNeedPeriodicIdleTime; crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff; crinfo[0].uIdleTimeInterval = 100; int hr = componentManager.FRegisterComponent(this, crinfo, out this._componentId); ErrorHandler.Succeeded(hr); } #endregion System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditorPane)); #region Hook Undo Manager // Attach an IOleUndoManager to our WindowFrame. Merely calling QueryService // for the IOleUndoManager on the site of our IVsWindowPane causes an IOleUndoManager // to be created and attached to the IVsWindowFrame. The WindowFrame automaticall // manages to route the undo related commands to the IOleUndoManager object. // Thus, our only responsibilty after this point is to add IOleUndoUnits to the // IOleUndoManager (aka undo stack). _undoManager = (IOleUndoManager)GetService(typeof(SOleUndoManager)); // In order to use the IVsLinkedUndoTransactionManager, it is required that you // advise for IVsLinkedUndoClient notifications. This gives you a callback at // a point when there are intervening undos that are blocking a linked undo. // You are expected to activate your document window that has the intervening undos. if (_undoManager != null) { IVsLinkCapableUndoManager linkCapableUndoMgr = (IVsLinkCapableUndoManager)_undoManager; if (linkCapableUndoMgr != null) { linkCapableUndoMgr.AdviseLinkedUndoClient(this); } } #endregion // hook up our XmlEditorService es = GetService(typeof(XmlEditorService)) as XmlEditorService; _store = es.CreateXmlStore(); _store.UndoManager = _undoManager; _model = _store.OpenXmlModel(new Uri(_fileName)); // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. _vsDesignerControl = new VsDesignerControl(_service, new ViewModel(_store, _model, this, _textBuffer)); base.Content = _vsDesignerControl; RegisterIndependentView(true); IMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as IMenuCommandService; if (null != mcs) { // Now create one object derived from MenuCommnad for each command defined in // the CTC file and add it to the command service. // For each command we have to define its id that is a unique Guid/integer pair, then // create the OleMenuCommand object for this command. The EventHandler object is the // function that will be called when the user will select the command. Then we add the // OleMenuCommand to the menu service. The addCommand helper function does all this for us. AddCommand(mcs, VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.NewWindow, new EventHandler(OnNewWindow), new EventHandler(OnQueryNewWindow)); AddCommand(mcs, VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.ViewCode, new EventHandler(OnViewCode), new EventHandler(OnQueryViewCode)); } }
/// <summary> /// This API supports the Entity Framework infrastructure and is not intended to be used directly from your code. /// </summary> /// <param name="model">This API supports the Entity Framework infrastructure and is not intended to be used directly from your code.</param> /// <returns>This API supports the Entity Framework infrastructure and is not intended to be used directly from your code.</returns> public override IEnumerable<IXmlChange> Changes(XmlModel model) { var m = model as SimpleXmlModel; SimpleTransactionLogger logger; if (resources.TryGetValue(m.Document, out logger)) { foreach (var cmd in logger.TxCommands) { yield return cmd.Change; } } }
/// <summary> /// Constructor /// </summary> /// <param name="xmlStore"></param> /// <param name="xmlModel"></param> /// <param name="provider"></param> /// <param name="buffer"></param> public ViewModel(Package pkg, XmlStore xmlStore, XmlModel xmlModel, IServiceProvider provider, IVsTextLines buffer) { _pkg = pkg; /// Initialize Asset Type List IList<AssetTypeItemClass> AssetTypeListItem = new List<AssetTypeItemClass>(); AssetTypeItemClass assetType = new AssetTypeItemClass("Other"); AssetTypeListItem.Add(assetType); assetType = new AssetTypeItemClass("Entry-point"); AssetTypeListItem.Add(assetType); assetType = new AssetTypeItemClass("Library"); AssetTypeListItem.Add(assetType); assetType = new AssetTypeItemClass("Executable"); AssetTypeListItem.Add(assetType); _assetTypeList = new CollectionView(AssetTypeListItem); if (xmlModel == null) throw new ArgumentNullException("xmlModel"); if (xmlStore == null) throw new ArgumentNullException("xmlStore"); if (provider == null) throw new ArgumentNullException("provider"); if (buffer == null) throw new ArgumentNullException("buffer"); this.BufferDirty = false; this.DesignerDirty = false; this._serviceProvider = provider; this._buffer = buffer; _dte = (DTE)_serviceProvider.GetService(typeof(DTE)); Array activeProjects = (Array)_dte.ActiveSolutionProjects; Project activeProject = (Project)activeProjects.GetValue(0); FileInfo activeProjectFileInfo = new FileInfo(activeProject.FullName); _activeProjectDirectory = activeProjectFileInfo.DirectoryName; this._xmlStore = xmlStore; // OnUnderlyingEditCompleted _editingScopeCompletedHandler = new EventHandler<XmlEditingScopeEventArgs>(OnUnderlyingEditCompleted); this._xmlStore.EditingScopeCompleted += _editingScopeCompletedHandler; // OnUndoRedoCompleted _undoRedoCompletedHandler = new EventHandler<XmlEditingScopeEventArgs>(OnUndoRedoCompleted); this._xmlStore.UndoRedoCompleted += _undoRedoCompletedHandler; this._xmlModel = xmlModel; // BufferReloaded _bufferReloadedHandler += new EventHandler(BufferReloaded); this._xmlModel.BufferReloaded += _bufferReloadedHandler; _localRIMFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Research In Motion\"; LoadModelFromXmlModel(); IList<ImageItemClass> IconImageList = new List<ImageItemClass>(); if ((_qnxSchema.icon != null) && (_qnxSchema.icon.image != null)) { string iconPNG_Path = ""; //added to avoid duplication. That's because I didn't find the template to remove teh ICON.PNG. foreach (string iconImage in _qnxSchema.icon.image) { ImageItemClass imageItem = new ImageItemClass(iconImage, getImagePath(iconImage), _activeProjectDirectory); if (imageItem.ImageName != null) //added because I didn't find the template to remove teh ICON.PNG. if (imageItem.ImageName == "icon.png") { if (iconPNG_Path != imageItem.ImagePath) //added because I didn't find the template to remove teh ICON.PNG. { IconImageList.Add(imageItem); iconPNG_Path = imageItem.ImagePath; } } else IconImageList.Add(imageItem); } } _iconImageList = new CollectionView(IconImageList); LoadPermissions(); IList<ImageItemClass> SplashScreenImageList = new List<ImageItemClass>(); if ((_qnxSchema.splashScreens != null) && (_qnxSchema.splashScreens.image != null)) { foreach (string splashScreenImage in _qnxSchema.splashScreens.image) { ImageItemClass imageItem = new ImageItemClass(splashScreenImage, getImagePath(splashScreenImage), _activeProjectDirectory); SplashScreenImageList.Add(imageItem); } } _splashScreenImageList = new CollectionView(SplashScreenImageList); IList<ConfigurationItemClass> ConfigurationList = new List<ConfigurationItemClass>(); ConfigurationItemClass configItem = new ConfigurationItemClass("All Configurations"); ConfigurationList.Add(configItem); foreach (qnxConfiguration config in _qnxSchema.configuration) { configItem = new ConfigurationItemClass(config.name); ConfigurationList.Add(configItem); } _configurationList = new CollectionView(ConfigurationList); IList<OrientationItemClass> OrientationList = new List<OrientationItemClass>(); OrientationItemClass OrientationItem = new OrientationItemClass("Default"); OrientationList.Add(OrientationItem); if (_qnxSchema.initialWindow.autoOrients == "") { _orientationItem = OrientationItem; } OrientationItem = new OrientationItemClass("Auto-orient"); OrientationList.Add(OrientationItem); if (_qnxSchema.initialWindow.autoOrients == "true") { _orientationItem = OrientationItem; } OrientationItem = new OrientationItemClass("Landscape"); OrientationList.Add(OrientationItem); if (_qnxSchema.initialWindow.aspectRatio == "landscape") { _orientationItem = OrientationItem; } OrientationItem = new OrientationItemClass("Portrait"); OrientationList.Add(OrientationItem); if (_qnxSchema.initialWindow.aspectRatio == "portrait") { _orientationItem = OrientationItem; } _orientationList = new CollectionView(OrientationList); }