public TimeLinePage(XmlNodeList milestones, MenuElement menuElement) { _totalItemNum = milestones.Count; _totalHeight = (_totalItemNum - 1) * 25; _menuElement = menuElement; texture = _menuElement.GetTextureById("timelinebg"); Debug.Log("w="+texture.width+", h="+texture.height); for (int i=0; i<_totalItemNum; i++){ TimeLineItem item = new TimeLineItem(_menuElement); item.setLabel(_menuElement.GetTextureById(milestones[i].Attributes["time"].Value)); addItem(item); Sprite itemImg = new Sprite(_menuElement.GetTextureById(milestones[i].Attributes["pic"].Value)); _itemImgAry.Add(itemImg); addChild(itemImg); Sprite itemTxt = new Sprite(_menuElement.GetTextureById(milestones[i].Attributes["text"].Value)); _itemTxtAry.Add(itemTxt); addChild(itemTxt); itemTxt.alpha = 0.0f; itemTxt.y = 640f; itemTxt.x = (_texture.width-itemTxt.width)/2-20; } this.addEventListner(GuiEvent.CHANGE, new EventDispatcher.CallBack(selectChangeHandler)); //this.addEventListner(GuiEvent.ENTER_FRAME,new EventDispatcher.CallBack(enterFrameHandler)); selectItemByIndex(_totalItemNum-1); }
public List<UserLeaderboard> getUsersData(XmlNodeList _nodelist) { List<UserLeaderboard> listUser = new List<UserLeaderboard>(); // foreach (XmlNode node in _nodelist) // { // foreach (XmlNode _childNode in node.ChildNodes) // { //// UserLeaderboard _usr = new UserLeaderboard(); // UserLeaderboard _usr = (UserLeaderboard)ScriptableObject.CreateInstance("UserLeaderboard"); // // _usr.name = _childNode.SelectSingleNode("name").InnerText; // _usr.userID = int.Parse(_childNode.Attributes.GetNamedItem("id").Value); // _usr.userName = _childNode.SelectSingleNode("name").InnerText; // _usr.userBestScore = int.Parse(_childNode.SelectSingleNode("score").InnerText); // _usr.timestamp = _childNode.SelectSingleNode("timestamp").InnerText; // if (node.Attributes.GetNamedItem("type").Value == GameModes.gameTypeList.Arcade.ToString()) // { // _usr.typeReg = GameModes.gameTypeList.Arcade; // } // if (node.Attributes.GetNamedItem("type").Value == GameModes.gameTypeList.Story.ToString()) // { // _usr.typeReg = GameModes.gameTypeList.Story; // } // // listUser.Add(_usr); // } // } return listUser; }
//DESC : 초기화 public XMLManager() { characterTable = LoadXml("Character", "NewDataSet", "Sheet1"); enemyTable = LoadXml("Enemy", "NewDataSet", "Sheet1"); stageTable = LoadXml("Stage", "NewDataSet", "Sheet1"); summonTable= LoadXml("SummonText", "NewDataSet", "Sheet1"); }
public XMLParser(String filePath) { dt = new DataTable(); dt.TableName = "tyontekijat"; dt.Columns.Add("etunimi", typeof(String)); dt.Columns.Add("sukunimi", typeof(String)); dt.Columns.Add("numero", typeof(String)); dt.Columns.Add("tyosuhde", typeof(String)); dt.Columns.Add("palkka", typeof(int)); dt.Columns.Add("vakituiset", typeof(int)); dt.Columns.Add("palkat yht", typeof(int)); for (int i = 0; i < dt.Columns.Count; i++) { dt.Columns[i].ReadOnly = false; } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); etunimiLista = xmlDoc.GetElementsByTagName("etunimi"); sukunimiLista = xmlDoc.GetElementsByTagName("sukunimi"); numeroLista = xmlDoc.GetElementsByTagName("numero"); tyosuhdeLista = xmlDoc.GetElementsByTagName("tyosuhde"); palkkaLista = xmlDoc.GetElementsByTagName("palkka"); }
//XmlDocument doc; void Awake() { doc.LoadXml(questions.text); XmlNode baseNode = doc.DocumentElement;// load the doc, dbPath is a string int nNodes = baseNode.ChildNodes.Count; // Use this for initialization number = Random.Range(1, 10); xnList = doc.SelectNodes("/Questions/Question[@id='" + number + "']"); while (!hit) { if (xnList.Count == 0) { number = Random.Range(1, 10); xnList = doc.SelectNodes("/Questions/Question[@id='" + number + "']"); } else { hit = true; } if (hit) { foreach (XmlNode node in xnList) { vraag = (node.SelectSingleNode("text").InnerText); antwoord1 = (node.SelectSingleNode("option1").InnerText); antwoord2 = (node.SelectSingleNode("option2").InnerText); antwoord3 = (node.SelectSingleNode("option3").InnerText); antwoord4 = (node.SelectSingleNode("option4").InnerText); goed = (node.SelectSingleNode("answer").InnerText); } } } }
public List<string> convertFromXmlNodeList(XmlNodeList xml) { List<string> list = new List<string> (); for (int i=0; i<xml.Count; i++) { list.Add( xml[i].InnerText); } return list; }
private static string getValue(XmlNodeList profileContent, string key) { foreach (XmlNode profileItems in profileContent) { if(profileItems.Name == key){ return profileItems.InnerText; } } return ""; }
public void InjectXmlNodeList(XmlNodeList nodeList) { XmlDocument doc = new XmlDocument(); xmlNode = doc.CreateElement("root"); foreach(XmlNode _node in nodeList) { xmlNode.AppendChild(_node); } RegisterEventHandlers(); }
private void ParseTileLayers(XmlNodeList tilelayersXmlNodeList) { foreach (XmlNode tileset in tilelayersXmlNodeList) { _tileLayers.Add(TileLayer.ParseTileLayer(tileset, this)); } //_tileLayersLoaded = true; Debug.Log(this); Debug.Log("Parsed TileLayers."); }
// Use this for initialization void Start() { var _mapXML = new XmlDocument(); _mapXML.LoadXml(Name.ToString()); //MapDrawer.MapController = this; _nodes = _mapXML.SelectNodes("//node"); Debug.Log("Nodes loaded: " + _nodes.Count); InitWorldBounds(); }
static XmlNode searchNode(int number, XmlNodeList nodes) { foreach (XmlNode n in nodes) { if(int.Parse(n.Attributes.GetNamedItem("id").Value) == number) { return n; } } return null; }
private void GetHighScoreInfo() { // Read highscore from xml file TextAsset ta = (TextAsset)Resources.Load ("HighScores",typeof(TextAsset)); m_Doc = new XmlDocument(); m_Doc.LoadXml(GetTextWithoutBOM(ta)); m_highScoreInfo = m_Doc.GetElementsByTagName("player"); /* foreach(XmlNode player in m_highScoreInfo){ Debug.Log(player["name"].InnerXml); Debug.Log (player["score"].InnerXml); }*/ }
public static void ReadFile(String path) { doc = new XmlDocument(); doc.Load(path); //加载Xml文件 rootElem = doc.DocumentElement; //获取根节点 wallNodes = rootElem.GetElementsByTagName("archi-wall"); polylines = rootElem.GetElementsByTagName("aux-polyline"); windowsNodes = rootElem.GetElementsByTagName("archi-window"); doorNodes = rootElem.GetElementsByTagName("archi-door"); archi_info = rootElem.GetElementsByTagName("archi-info"); sizex = float.Parse(((XmlElement)archi_info[0]).GetAttribute("sizex"))/scalar; sizez = float.Parse(((XmlElement)archi_info[0]).GetAttribute("sizez"))/scalar; }
private void getObjects() { Debug.Log("Start getting item"); clearObjects(); setupObjects(); initXML(); itemNodes = xmlDoc.SelectNodes("map/objectgroup"); string path = "Prefabs/03Level/"; Vector2 offset = new Vector2 (6f ,-1f); foreach (XmlNode node in itemNodes) { GameObject objectContainer = FETool.findWithinChildren(this.gameObject, node.Attributes.GetNamedItem("name").Value); foreach (XmlNode children in node.ChildNodes) { if(children.Attributes.GetNamedItem("type") != null) { Debug.Log("step1"); string childType = children.Attributes.GetNamedItem("type").Value; if (Resources.Load(path + childType) != null) { GameObject _instance = /*PrefabUtility.InstantiatePrefab*/Instantiate(Resources.Load(path + childType)) as GameObject ; if (objectContainer.name != "BUG") { _instance.transform.parent = objectContainer.transform;} float _posX = float.Parse(children.Attributes.GetNamedItem("x").Value) / 50f; float _posY = (float.Parse(children.Attributes.GetNamedItem("y").Value) / 50f) *-1f; if (children.Attributes.GetNamedItem("width") != null) { if (childType == LevelBrick.brickEnum.Ditch.ToString()) { float _objWidth = float.Parse(children.Attributes.GetNamedItem("width").Value); float _objHeight = float.Parse(children.Attributes.GetNamedItem("height").Value); _instance.transform.localScale = new Vector3(_objWidth / 50f, _objHeight / 50f, 30f); } } if (children.Attributes.GetNamedItem("name") != null) { _instance.name = children.Attributes.GetNamedItem("name").Value; } _instance.transform.position = new Vector3 (_posX + offset.x, _posY + offset.y , -5f); Debug.Log("Created a " + children.Attributes.GetNamedItem("type").Value + " at position (X" + _instance.transform.position.x + "/Y" +_instance.transform.position.y+")"); } else { Debug.Log("Couldn't find prefab "+ children.Attributes.GetNamedItem("type").Value); } } } } Debug.Log("Finish getting item"); }
public static Tile[,] ParseTiles(XmlNodeList tilesXmlNodeList, TileMap map, int width, int height) { var tiles = new Tile[width, height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { tiles[x, y] = Tile.ParseTile(tilesXmlNodeList.Item(x * width + y), map, x, y); } } return tiles; }
public void LoadDialogue(string path) { if (m_Running) { m_Running = false; ClearDialogue(); } m_Running = true; DialoguePath = path; DialoguePath = "Assets/Resources/Text/Dialogue/" + DialoguePath; m_DialogueChain.Load(DialoguePath); m_DialogueLines = m_DialogueChain.SelectNodes("/root/line"); PlayDialogue(); }
public Cartelera getCartelCine() { doc = new XmlDocument(); try { doc.Load("http://www.cinepolis.com.mx/iphone/xml-iphone.aspx?query=cartelera&ci=" + cartel.CiudadID); } catch (Exception e) { return null; } try { complejoInfo = doc.SelectSingleNode("//Cartelera//Complejo[@Complejoid='" + cartel.ComplejoID + "']"); cartel.Complejo = complejoInfo.Attributes.GetNamedItem("Nombre").Value; cartel.Latitud = complejoInfo.ChildNodes[1].InnerText.Trim(); cartel.Longitud = complejoInfo.ChildNodes[2].InnerText.Trim(); Complejos_peli = doc.SelectNodes("//Cartelera//Complejo[@Complejoid='" + cartel.ComplejoID + "']/Pelicula"); foreach (XmlNode complejo_peli in Complejos_peli) { peli = new Pelicula(); string Horario_Peli = ""; peli.PeliculaID = complejo_peli.FirstChild.InnerText; Complejos_hora = doc.SelectNodes("//Cartelera//Complejo/Pelicula[Peliculaid='" + peli.PeliculaID + "']/Horarios/Horario"); foreach (XmlNode horario in Complejos_hora) { Horario_Peli += horario.InnerText + " - "; } peliculaInfo = doc.SelectSingleNode("//Peliculas//Pelicula[@Peliculaid='" + peli.PeliculaID + "']"); peli.Nombre = peliculaInfo.Attributes.GetNamedItem("Nombre").Value; peli.Clasificacion = peliculaInfo.ChildNodes[1].InnerText; peli.Calificacion = peliculaInfo.ChildNodes[4].InnerText; peli.Descripcion = peliculaInfo.ChildNodes[6].InnerText; peli.Director = peliculaInfo.ChildNodes[7].InnerText; peli.Actor = peliculaInfo.ChildNodes[8].InnerText; peli.Duracion = peliculaInfo.ChildNodes[16].InnerText; peli.Trailer = peliculaInfo.ChildNodes[19].InnerText; peli.Horarios = Horario_Peli; cartel.Peliculas.Add(peli); } } catch (Exception e) { return null;} return cartel; }
private void Button_Click_1(object sender, RoutedEventArgs e) { //Tile test ... var tileContent = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareBlock); tileLines = tileContent.SelectNodes("tile/visual/binding/text"); tileLines[0].InnerText = inputBox.Text.Substring(0,2); notification = new TileNotification(tileContent); updater = TileUpdateManager.CreateTileUpdaterForApplication(); //updater.EnableNotificationQueue(true); MakeRequests(inputBox.Text); xivelyOutput.Text = "Requested " + inputBox.Text + " from Xively at " + "" + DateTime.Now.ToString("hh:mm:ss"); }
static bool getDataFromXmlFile(string strXmlFileToProcess) { try { XmlDocument xdPlugInXmlFile = new XmlDocument(); xdPlugInXmlFile.Load(strXmlFileToProcess); strPathToTemplatePowerpointFile = Path.Combine(Environment.CurrentDirectory,xdPlugInXmlFile.GetElementsByTagName("PathToTemplatePowerpointFile")[0].InnerText); strPathToXmlFileWithData = xdPlugInXmlFile.GetElementsByTagName("PathToXmlFileWithData")[0].InnerText; xnlRISO_Report_Pages = xdPlugInXmlFile.GetElementsByTagName("RISO_Report_Page"); return true; } catch (Exception ex) { MessageBox.Show("Error in getDataFromXmlFile: "+ ex.Message); return false; } }
// Use this for initialization public MainMenu(XmlNodeList nodes) { _bg = new Sprite(Resources.Load("mainMenu/component/mainMenuBg", typeof(Texture2D)) as Texture2D); _bg.width = _menuWidth; _bg.height = _menuHeight; addChild(_bg); for (int i=0; i<nodes.Count; i++){ GuiMenuItem item = new GuiMenuItem(); item.selectedTexture = Resources.Load("mainMenu/icon/" + nodes[i].Attributes["icon"].Value+"-b", typeof(Texture2D)) as Texture2D; item.defaultTexture = Resources.Load("mainMenu/icon/" + nodes[i].Attributes["icon"].Value, typeof(Texture2D)) as Texture2D; if (nodes[i].Attributes["iOSNativeCode"] != null){ item.iOSNativeCode = nodes[i].Attributes["iOSNativeCode"].Value; typeof(UIBinding).InvokeMember("ActivateUI"+item.iOSNativeCode, BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[]{ }); typeof(UIBinding).InvokeMember("DeactivateUI"+item.iOSNativeCode, BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[]{ }); } addItem(item); } }
//private string level{get;set;} // Use this for initialization void Start() { levelArray = new List<string> (); levelDoc = new XmlDocument (); TextAsset xmlfile = Resources.Load ("levels", typeof(TextAsset)) as TextAsset; levelDoc.LoadXml (xmlfile.text); levelist = levelDoc.GetElementsByTagName ("level"); foreach( XmlNode leveldata in levelist){ XmlNodeList levelinfo = leveldata.ChildNodes; foreach(XmlNode data in levelinfo){ if(data.Name == "setup"){ levelArray.Add(data.InnerText); // if(data.Name=="levelname") // level=data.InnerText; } } } }
public SubMenu(XmlNodeList nodes) { _nodes = nodes; _bg = new Sprite(Resources.Load("mainmenu/component/subMenuBg", typeof(Texture2D)) as Texture2D); _bg.width = _menuWidth; _bg.height = _menuHeight; addChild(_bg); _subMenuBg = new SubMenuBg(); _subMenuBg.y = 6; addChild(_subMenuBg); for (int i=0; i<nodes.Count; i++){ GuiMenuItem item = new GuiMenuItem(); item.selectedTexture = Resources.Load("mainmenu/sub/"+nodes[i].Attributes["icon"].Value, typeof(Texture2D)) as Texture2D; item.defaultTexture = Resources.Load("mainmenu/sub/"+nodes[i].Attributes["icon"].Value, typeof(Texture2D)) as Texture2D; addItem(item); } }
public override void OnInspectorGUI() { DrawDefaultInspector(); DataMakerXmlNodeListProxy _target = target as DataMakerXmlNodeListProxy; if (_target._FsmXmlNodeList!=null) { if (!_target._FsmXmlNodeList.Value.Equals(nodeListCache) ){ nodeListCache = _target._FsmXmlNodeList.Value; content = DataMakerXmlUtils.XmlNodeListToString(nodeListCache); } DataMakerEditorGUILayoutUtils.feedbackLabel("Xml Source Valid",DataMakerEditorGUILayoutUtils.labelFeedbacks.OK); _scroll = DataMakerEditorGUILayoutUtils.StringContentPreview(_scroll,content); }else{ DataMakerEditorGUILayoutUtils.feedbackLabel("Xml Source Invalid",DataMakerEditorGUILayoutUtils.labelFeedbacks.ERROR); } }
/// <summary> find xml nodes whitch have same name </summary> /// <param name="name">node name</param> /// <returns>matched xml nodes</returns> public XmlNodeList FindElementsByName(string name) { XmlNodeList result = null; if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); using (SqlConnection con = new SqlConnection(connectionString)) { string sql = string.Format(@"SELECT * FROM {0} WHERE NodeName = @name", TableName); SqlParameter para = new SqlParameter("@name", name); con.Open(); SqlCommand cmd = new SqlCommand(sql, con); cmd.Parameters.Add(para); SqlDataReader reader = cmd.ExecuteReader(); if(reader.HasRows)result = new XmlNodeList(); while (reader.Read()) { result.Add(CreateReadedData(reader)); } reader.Close(); con.Close(); } return result; }
public TrainingXml(String filePath) { dt = new DataTable(); dt.TableName = "harjoitukset"; dt.Columns.Add("hiihtäjä", typeof(String)); dt.Columns.Add("päivämäärä", typeof(String)); dt.Columns.Add("aika", typeof(String)); dt.Columns.Add("kilometrit", typeof(String)); for (int i = 0; i < dt.Columns.Count; i++) { dt.Columns[i].ReadOnly = false; } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filePath); nimiLista = xmlDoc.GetElementsByTagName("hiihtäjä"); pvmLista = xmlDoc.GetElementsByTagName("päivämäärä"); aikaLista = xmlDoc.GetElementsByTagName("aika"); kilometriLista = xmlDoc.GetElementsByTagName("kilometrit"); }
// packet received void OnPacketReceived(object sender, string Packet) { xmlDoc.LoadXml(Packet); rigidBodyList = xmlDoc.GetElementsByTagName("Bone"); //Initialize the rigid body data arrays once if(receivedFirstRigidBodyPacket == false) { for(int index=0; index<rigidBodyList.Count; index++) { rigidBodyIDs = new int[rigidBodyList.Count]; rigidBodyPositions = new Vector3[rigidBodyList.Count]; rigidBodyQuaternions = new Quaternion[rigidBodyList.Count]; } receivedFirstRigidBodyPacket = true; } //Loop through the packet for the rigid body data for(int index=0; index<rigidBodyList.Count; index++) { rigidBodyIDs[index] = System.Convert.ToInt32(rigidBodyList[index].Attributes["ID"].InnerText); //Rigid Body Position rigidBodyPositions[index].x = -((float) System.Convert.ToDouble(rigidBodyList[index].Attributes["x"].InnerText)) + origin.position.x; rigidBodyPositions[index].y = (float) System.Convert.ToDouble(rigidBodyList[index].Attributes["y"].InnerText) + origin.position.y; rigidBodyPositions[index].z = (float) System.Convert.ToDouble(rigidBodyList[index].Attributes["z"].InnerText) + origin.position.z; //Rigid Body Quaternion Orientation //Convert coordinates systems from Motive to Unity rigidBodyQuaternions[index].x = (float) System.Convert.ToDouble(rigidBodyList[index].Attributes["qx"].InnerText); rigidBodyQuaternions[index].y = -((float)System.Convert.ToDouble(rigidBodyList[index].Attributes["qy"].InnerText)); rigidBodyQuaternions[index].z = -((float)System.Convert.ToDouble(rigidBodyList[index].Attributes["qz"].InnerText)); rigidBodyQuaternions[index].w = (float)System.Convert.ToDouble(rigidBodyList[index].Attributes["qw"].InnerText); //Add the origin roatation rigidBodyQuaternions[index] = origin.rotation * rigidBodyQuaternions[index]; } }
void Start() { levelArray = new List<string> (); levelDoc = new XmlDocument(); TextAsset xmlfile = Resources.Load ("levels", typeof(TextAsset)) as TextAsset; levelDoc.LoadXml (xmlfile.text); levelList = levelDoc.GetElementsByTagName("level"); foreach (XmlNode leveldata in levelList) { XmlNodeList levelinfo = leveldata.ChildNodes; Debug.Log (levelList.Count); foreach (XmlNode data in levelinfo) { Debug.Log(data.Name); if(data.Name == "setup") { Debug.Log(data.InnerText); levelArray.Add(data.InnerText); } } } this.gameObject.GetComponent<GameManager>().Initialise(levelArray.Count); }
public static string XmlNodeListToString(XmlNodeList nodeList, int indentation) { if (nodeList==null) { return "-- NULL --"; } using (var sw = new StringWriter()) { using (var xw = new XmlTextWriter(sw)) { xw.Formatting = Formatting.Indented; xw.Indentation = indentation; xw.WriteRaw("<result>"); foreach(XmlNode node in nodeList) { node.WriteTo(xw); } xw.WriteRaw("</result>"); } return sw.ToString(); } }
private XmlDocument ProcessProvideAndRegisterDocumentSet(XmlDocument xmlDocRequest, MessageVersion msgVersion, out StringDictionary atnaParameterValues) { XmlDocument xmlDocRegistryRequest = null; XmlDocument xmlDocResponse = null; Message registryMessage = null; XmlDocument xmlDocRegistryResponse = null; RepositoryLogic repositoryLogic = null; XmlElement eltProvideAndRegDocSet = null; XmlNode nodeSubmitObjectsRequest = null; XmlNodeList nodeListExtrinsicObject = null; XmlNodeList nodeListDocument = null; XmlNode nodeSubmissionSet = null; XmlNode nodeExternalIdentifier = null; List <DocumentEntry> lstDocumentEntry = null; StringBuilder sbMetaData = null; string xpathExternalIdentifierDocument = @".//*[local-name()='ExtrinsicObject'][@id='$id$']/*[local-name()='ExternalIdentifier'][@identificationScheme='$identificationScheme$']"; string xpath = null; string entryUUID = null; string uniqueID = null; string eventOutcomeIndicator = "0"; atnaParameterValues = new StringDictionary(); try { repositoryLogic = new RepositoryLogic(); xpathExternalIdentifierDocument = xpathExternalIdentifierDocument.Replace("$identificationScheme$", GlobalValues.XDSDocumentEntry_uniqueIdUUID); eltProvideAndRegDocSet = xmlDocRequest.DocumentElement; nodeListExtrinsicObject = eltProvideAndRegDocSet.SelectNodes(".//*[local-name()='ExtrinsicObject']"); nodeListDocument = eltProvideAndRegDocSet.SelectNodes(".//*[local-name()='Document']"); nodeSubmissionSet = eltProvideAndRegDocSet.SelectSingleNode("//*[local-name()='SubmitObjectsRequest']/*[local-name()=\"RegistryObjectList\"]/*[local-name()='RegistryPackage']/*[local-name()='ExternalIdentifier'][@identificationScheme='urn:uuid:96fdda7c-d067-4183-912e-bf5ee74998a8']/@value"); if (nodeSubmissionSet != null) { atnaParameterValues.Add("$SubmissionSet.UniqueID$", nodeSubmissionSet.Value); } //Proceed further only if any ExtrinsicObject Exists(with attachments) if (nodeListExtrinsicObject == null) { throw new Exception(); } //if (repositoryLogic.IsMissingDocumentAttachment(nodeListDocument, eltProvideAndRegDocSet)) if (repositoryLogic.IsMissingDocumentAttachment(eltProvideAndRegDocSet)) { throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSMissingDocumentAttachment); } //if (repositoryLogic.IsMissingDocumentMetadata(nodeListExtrinsicObject, eltProvideAndRegDocSet)) if (repositoryLogic.IsMissingDocumentMetadata(eltProvideAndRegDocSet)) { throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSMissingDocumentMetadata); } #if debug if (!repositoryLogic.IsSchemaValid(xmlDocMsgBody)) { throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSInvalidRequest); } #endif if (repositoryLogic.IsDuplicateUniqueID(eltProvideAndRegDocSet)) { throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSRepositoryDuplicateUniqueIdInMessage); } if (nodeListExtrinsicObject.Count > 0 && eltProvideAndRegDocSet.SelectNodes(@"//*[local-name()='Document']").Count > 0) { //No document OR Metadata is Missing lstDocumentEntry = new List <DocumentEntry>(); sbMetaData = new StringBuilder(); foreach (XmlNode node in nodeListExtrinsicObject) { DocumentEntry objDocumentEntry = new DocumentEntry(); if (node.Attributes["mimeType"].Value == string.Empty) { throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSRepositoryMetadataError); } objDocumentEntry.MimeType = node.Attributes["mimeType"].Value; entryUUID = node.Attributes["id"].Value; xpath = xpathExternalIdentifierDocument.Replace("$id$", node.Attributes["id"].Value); nodeExternalIdentifier = eltProvideAndRegDocSet.SelectSingleNode(xpath); uniqueID = nodeExternalIdentifier.Attributes["value"].Value; if (string.IsNullOrEmpty(uniqueID)) { throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSRepositoryMetadataError); } if (!repositoryLogic.IsValidUniqueID(uniqueID)) { throw new Exception(GlobalValues.CONST_ERROR_CODE_XDSInvalidRequest); } objDocumentEntry.EntryUUID = entryUUID; objDocumentEntry.UniqueID = uniqueID; objDocumentEntry.Hash = repositoryLogic.GetHashCode(xmlDocRequest, entryUUID); objDocumentEntry.Content = repositoryLogic.GetDocumentContentStream(xmlDocRequest, entryUUID); objDocumentEntry.Size = (int)objDocumentEntry.Content.Length; lstDocumentEntry.Add(objDocumentEntry); sbMetaData.Append(node.OuterXml); } //Logging the Repository Data objDocumentRepositoryLog.RequestMetadata = sbMetaData.ToString(); using (TransactionScope provideAndRegSetBScope = new TransactionScope()) { //Information Logged in the Document Repository Log objDocumentRepositoryLog.EndTime = DateTime.Now; objDocumentRepositoryLog.Result = "OK"; int noOfRows = repositoryLogic.LogRepositoryData(objDocumentRepositoryLog); for (int docElement = 0; docElement < lstDocumentEntry.Count; docElement++) { string sStorageUniqueIdentifier = string.Empty; DocumentEntry objDocEntry = lstDocumentEntry[docElement]; sStorageUniqueIdentifier = SQLServerStorageService.SaveDocument(objDocEntry.Content, objDocEntry.UniqueID); //Save Metadata repositoryLogic.SaveMetaData(objDocEntry); //Insert into Document Entry Log repositoryLogic.LogDocumentEntry(); } //Create SLots for Repository ID,,Hash and Size and send those to //Register document Set B //this Array list already contains all ID's if (lstDocumentEntry.Count > 0) { string repositoryUniqueId = repositoryLogic.GetRepositoryUniqueID("repositoryUniqueID"); string repositoryURI = string.Empty; for (int docID = 0; docID < lstDocumentEntry.Count; docID++) { DocumentEntry objDocumentEntry = lstDocumentEntry[docID]; //Creates Slots to add Medatada repositoryUniqueId xmlDocRequest = repositoryLogic.CreateRepositorySlotElement(xmlDocRequest, "repositoryUniqueId", repositoryUniqueId, objDocumentEntry.EntryUUID); //Creates Slots to add Medatada hash xmlDocRequest = repositoryLogic.CreateRepositorySlotElement(xmlDocRequest, "hash", objDocumentEntry.Hash, objDocumentEntry.EntryUUID); //Creates Slots to add Medatada size xmlDocRequest = repositoryLogic.CreateRepositorySlotElement(xmlDocRequest, "size", objDocumentEntry.Content.Length.ToString(), objDocumentEntry.EntryUUID); //Creates Slots to add Medatada URI xmlDocRequest = repositoryLogic.CreateRepositorySlotElement(xmlDocRequest, "URI", repositoryURI, objDocumentEntry.EntryUUID); } } //Message to be sent to Registry try { //Sample RegistryResponse - <RegistryResponse xmlns="urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0" />; //Call the XDSRegistry Service Message provideAndResgiterSetInput = null; string xdsRegistryEndpointName = CommonUtility.GetXDSRegistryEndpointName(); xmlDocRegistryRequest = new XmlDocument(); nodeSubmitObjectsRequest = xmlDocRequest.SelectSingleNode(@"//*[local-name()='SubmitObjectsRequest']"); xmlDocRegistryRequest.LoadXml(nodeSubmitObjectsRequest.OuterXml); XDSRegistry.XDSRegistryClient objRegsitryClient = new Microsoft.IHE.XDS.DocumentRepository.XDSRegistry.XDSRegistryClient(xdsRegistryEndpointName); provideAndResgiterSetInput = Message.CreateMessage(msgVersion, GlobalValues.CONST_ACTION_REGISTERDOCUMENTSETB, new XmlNodeReader(xmlDocRegistryRequest)); registryMessage = objRegsitryClient.RegisterDocumentSet(provideAndResgiterSetInput); } catch { throw new Exception("XDSRegistryNotAvailable"); } xmlDocRegistryResponse = new XmlDocument(); xmlDocRegistryResponse.Load(registryMessage.GetReaderAtBodyContents()); XmlNode errorList = xmlDocRegistryResponse.SelectSingleNode(@"//*[local-name()='RegistryError']"); string errorCode = null; if (errorList != null) { errorCode = errorList.Attributes["errorCode"].Value; } //Move this outside TransactionScope...the log entry is rolled back //Code block within TransactionScope should be //if (errorCode == null) //{ // provideAndRegSetBScope.Complete(); //} //Code block outside TransactionScope should be //if (errorCode != null) //{ // repositoryLogic.LogRolledBackData(objDocumentRepositoryLog, errorCode); // //ATNA Failure Code // eventOutcomeIndicator = "8"; //} if (errorCode != null) { repositoryLogic.LogRolledBackData(objDocumentRepositoryLog, errorCode); //ATNA Failure Code eventOutcomeIndicator = "8"; } else { provideAndRegSetBScope.Complete(); } //Assign Registry Response to Repository Response xmlDocResponse = xmlDocRegistryResponse; //Transaction is completed } } else { //Get Message from Registry try { //Sample RegistryResponse - <RegistryResponse xmlns="urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0" />; //Call the XDSRegistry Service Message msgProvideAndResgiterSetInput = null; string xdsRegistryEndpointName = CommonUtility.GetXDSRegistryEndpointName(); xmlDocRegistryRequest = new XmlDocument(); nodeSubmitObjectsRequest = xmlDocRequest.SelectSingleNode(@"//*[local-name()='SubmitObjectsRequest']"); xmlDocRegistryRequest.LoadXml(nodeSubmitObjectsRequest.OuterXml); XDSRegistry.XDSRegistryClient objRegsitryClient = new Microsoft.IHE.XDS.DocumentRepository.XDSRegistry.XDSRegistryClient(xdsRegistryEndpointName); msgProvideAndResgiterSetInput = Message.CreateMessage(msgVersion, GlobalValues.CONST_ACTION_REGISTERDOCUMENTSETB, new XmlNodeReader(xmlDocRegistryRequest)); registryMessage = objRegsitryClient.RegisterDocumentSet(msgProvideAndResgiterSetInput); } catch { throw new Exception("XDSRegistryNotAvailable"); } xmlDocRegistryResponse = new XmlDocument(); xmlDocRegistryResponse.Load(registryMessage.GetReaderAtBodyContents()); XmlNode errorList = xmlDocRegistryResponse.SelectSingleNode(@"//*[local-name()='RegistryError']"); string errorCode = null; if (errorList != null) { errorCode = errorList.Attributes["errorCode"].Value; } if (errorCode != null) { repositoryLogic.LogRolledBackData(objDocumentRepositoryLog, errorCode); //ATNA Failure Code eventOutcomeIndicator = "8"; } //Assign Registry Response to Repository Response xmlDocResponse = xmlDocRegistryResponse; } } catch { throw; } atnaParameterValues.Add("$EventIdentification.EventOutcomeIndicator$", eventOutcomeIndicator); return(xmlDocResponse); }
public static brushData importBrush(String filename, int NUM_TEXTURE_TOTAL) { brushData data = new brushData(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filename); data.textures = new LinkedList <textureData>(); for (int index = 1; index <= NUM_TEXTURE_TOTAL; index++) { XmlNodeList node = xmlDoc.GetElementsByTagName("texture" + index); if (node[0] != null) { data.textures.AddLast(readTextureElement(node[0])); } else { break; } } //Grass XmlElement grassElem = (XmlElement)xmlDoc.GetElementsByTagName("Grass")[0]; string grassOptionStr = grassElem.GetAttribute("grassOption"); if (grassOptionStr == grassOption.NoGrass.ToString()) { data.grassOption = grassOption.NoGrass; } else if (grassOptionStr == grassOption.Paint.ToString()) { data.grassOption = grassOption.Paint; } else { throw new Exception("Wrong grass option"); } data.grassSize = int.Parse(grassElem.GetAttribute("bladeSize")); data.grassSizeVariation = int.Parse(grassElem.GetAttribute("bladeSizeVariation")); data.grassCoverage = int.Parse(grassElem.GetAttribute("coverage")); data.grassDensity = int.Parse(grassElem.GetAttribute("density")); data.grassTexture = new String[3]; string val; for (int index = 0; index < 3; index++) { if (grassElem.HasAttribute("grassTexture" + (index + 1))) { val = grassElem.GetAttribute("grassTexture" + (index + 1)); data.grassTexture[index] = val; } } //Brush data XmlElement brushElem = (XmlElement)xmlDoc.GetElementsByTagName("Brush_Data")[0]; data.innerCircle = int.Parse(brushElem.GetAttribute("inner")); data.outerCircle = int.Parse(brushElem.GetAttribute("outer")); // Colour XmlElement colourElem = (XmlElement)xmlDoc.GetElementsByTagName("Colour")[0]; data.col = Color.FromArgb(int.Parse(colourElem.InnerXml)); string colourOptionStr = colourElem.GetAttribute("option"); if (colourOptionStr == colourOption.Colour.ToString()) { data.colourOption = colourOption.Colour; } else if (colourOptionStr == colourOption.NoColour.ToString()) { data.colourOption = colourOption.NoColour; } else { throw new Exception("Wrong colour option"); } data.colourCoverage = int.Parse(colourElem.GetAttribute("coverage")); data.colourPresure = int.Parse(colourElem.GetAttribute("presure")); XmlElement randomizeElement = (XmlElement)xmlDoc.GetElementsByTagName("Random")[0]; if (randomizeElement != null) { data.randomize = bool.Parse(randomizeElement.GetAttribute("randomize")); } return(data); }
private async void buttonReplace_Click(object sender, EventArgs el) { try { // Bouton en cours buttonReplace.Enabled = false; buttonReplace.BackColor = Color.White; // Backup if (checkBoxBackup.Checked == true) { buttonReplace.Text = "Backup..."; File.Delete(pathDirectoryName + "\\" + name + "BACKUP"); File.Delete(pathDirectoryName + "\\" + "SaveGameInfoBACKUP"); File.Copy(pathfileName, pathDirectoryName + "\\" + name + "BACKUP"); File.Copy(pathDirectoryName + "\\SaveGameInfo", pathDirectoryName + "\\" + "SaveGameInfoBACKUP"); } XmlNodeList[] nodeTab = new XmlNodeList[]{ // Lieux où chercher (Name) docName.SelectNodes("/SaveGame/locations/GameLocation/objects/item/value/Object/items/Item"), docName.SelectNodes("/SaveGame/player/items/Item"), docName.SelectNodes("/SaveGame/locations/GameLocation/buildings/Building/indoors/name"), docName.SelectNodes("/SaveGame/locations/GameLocation/buildings/Building/buildingType"), docName.SelectNodes("/SaveGame/player/craftingRecipes/item/key/string"), docName.SelectNodes("/SaveGame/locations/GameLocation/objects/item/value/Object/Name"), docName.SelectNodes("/SaveGame/locations/GameLocation/objects/item/value/Object/name"), docName.SelectNodes("/SaveGame/locations/GameLocation/objects/item/value/Object/heldObject/Name"), docName.SelectNodes("/SaveGame/locations/GameLocation/objects/item/value/Object/heldObject/name"), docName.SelectNodes("/SaveGame/locations/GameLocation/buildings/Building/indoors/objects/item/value/Object/Name"), docName.SelectNodes("/SaveGame/locations/GameLocation/buildings/Building/indoors/objects/item/value/Object/name"), // Lieux où chercher (Game) docGame.SelectNodes("/Farmer/items/Item"), docGame.SelectNodes("/Farmer/craftingRecipes/item/key/string"), }; // Remplacements await Task.Run(() => { for (int i = 0; i < nodeTab.GetLength(0); i++) { mOperation.Remplace3(nodeTab[i], comboBox1.Text, buttonReplace); } }); // Sauvegarde docName.Save(pathfileName); docGame.Save(pathDirectoryName + "\\SaveGameInfo"); // Changements tête bouton buttonReplace.Enabled = false; buttonReplace.BackColor = Color.White; buttonReplace.Text = Translate_Terminé(); } catch { buttonReplace.Enabled = false; buttonReplace.BackColor = Color.White; buttonReplace.Text = Translate_Erreur(); } }
static void Main(string[] args) { try { Console.WriteLine("Binary"); FinalExam fi = new FinalExam(); fi.countOfQuest = 73; BinaryFormatter formatter = new BinaryFormatter(); using (FileStream fs = new FileStream("finalExam.txt", FileMode.OpenOrCreate)) { formatter.Serialize(fs, fi); } using (FileStream fs = new FileStream("finalExam.txt", FileMode.OpenOrCreate)) { FinalExam final = (FinalExam)formatter.Deserialize(fs); Console.WriteLine($"Count of Questions: {final.countOfQuest}"); } Console.WriteLine("soap"); SoapFormatter soapFormatter = new SoapFormatter(); using (Stream fStream = new FileStream("finalExam.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { soapFormatter.Serialize(fStream, fi); } using (FileStream fs = new FileStream("finalExam.txt", FileMode.OpenOrCreate)) { FinalExam final = (FinalExam)soapFormatter.Deserialize(fs); Console.WriteLine($"Count of Questions: {final.countOfQuest}"); } Console.WriteLine("json"); DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(FinalExam)); using (FileStream fs = new FileStream("finalExam.json", FileMode.OpenOrCreate)) { jsonFormatter.WriteObject(fs, fi); } using (FileStream fs = new FileStream("finalExam.json", FileMode.OpenOrCreate)) { FinalExam final = (FinalExam)jsonFormatter.ReadObject(fs); Console.WriteLine($"Count of Questions: {final.countOfQuest}"); } Console.WriteLine("xml"); XmlSerializer xSer = new XmlSerializer(typeof(FinalExam)); using (FileStream fs = new FileStream("finalExam.xml", FileMode.OpenOrCreate)) { xSer.Serialize(fs, fi); } using (FileStream fs = new FileStream("finalExam.xml", FileMode.OpenOrCreate)) { FinalExam final = xSer.Deserialize(fs) as FinalExam; Console.WriteLine($"Count of Questions: {final.countOfQuest}"); } // 2 задание Console.WriteLine("\nArray"); FinalExam[] finalExams = new FinalExam[] { new FinalExam(44), fi, new FinalExam(82), new FinalExam(40) }; finalExams[0].Subject = "Math"; finalExams[1].Subject = "Biology"; finalExams[2].Subject = "Chemistry"; finalExams[3].Subject = "PE"; XmlSerializer xSer2 = new XmlSerializer(typeof(FinalExam[])); //Для сериализации объектов в файлы xml using (FileStream fs = new FileStream("Exams.xml", FileMode.OpenOrCreate)) { xSer2.Serialize(fs, finalExams); } using (FileStream fs = new FileStream("Exams.xml", FileMode.OpenOrCreate)) { FinalExam[] fis = (FinalExam[])xSer2.Deserialize(fs); foreach (FinalExam fe in fis) Console.WriteLine($"Count of Questions: {fe.countOfQuest}"); } // 3 задание Console.WriteLine(); XmlDocument xDoc = new XmlDocument(); xDoc.Load("Exams.xml"); XmlElement xRoot = xDoc.DocumentElement; XmlNode childnode = xRoot.SelectSingleNode("FinalExam[Subject='Math']"); if (childnode != null) Console.WriteLine(childnode.OuterXml); Console.WriteLine(); XmlNodeList childnodes = xRoot.SelectNodes("FinalExam[countOfQuest>45]"); foreach (XmlNode n in childnodes) Console.WriteLine(n.OuterXml); // 4 задание XDocument xDocument = XDocument.Load("exams.xml"); var exs = xDocument.Element("ArrayOfFinalExam").Elements("FinalExam").Select(q => new { subject = q.Element("Subject").Value, count = q.Element("countOfQuest").Value, }); using (StreamWriter sw = new StreamWriter("second.xml")) foreach (var x in exs) { sw.WriteLine($"{x.subject} — {x.count} questions;"); } Console.WriteLine(); Console.ReadKey(); } catch (Exception e) { Console.WriteLine("Error " + e.Message); } }
static bool LoadData(string afile) { XmlDocument xmlDOc = new XmlDocument(); xmlDOc.Load(afile); int row = 0; XmlNodeList nodeList = xmlDOc.SelectNodes(@"data/row/col"); //判斷節點存在 if (nodeList == null) { ErrorLog("載入的XML檔案" + afile + ",不存在data/row/col結構! -- 終止執行"); return(false); } foreach (XmlNode oneNode in nodeList) { row++; if (oneNode.Attributes["name"] != null) { string name = oneNode.Attributes["name"].Value; dr[name] = oneNode.InnerText; } else { ErrorLog("第" + row.ToString() + "個col發現沒有name屬性"); } } if (dr["detail"] == "1") { XmlNodeList nodeList2 = xmlDOc.SelectNodes(@"detail/products"); //判斷節點存在 if (nodeList2 == null) { ErrorLog("載入的XML檔案" + afile + ",不存在detail/products結構! -- 終止執行"); return(false); } foreach (XmlNode node in nodeList2) { string product = ""; for (int i = 0; i < node.ChildNodes.Count; i++) { string text = node.ChildNodes[i].InnerText; if (i == 0) { product += text + "\n"; } else { product += text + "\t"; } if (i == 3) { products.Add(product + "\n"); } } } } return(true); }
private void Load(string Filename, XmlDocument Document, XmlNamespaceManager NSMgr) { Log("Message", "Load", String.Format("Filename : {0}", Filename)); IsFileImportLoadingRunning = true; //Store the filename we're using this.Filename = Filename; //Create an XML document object from the file specified Document.Load(Filename); //Find the Header node XmlNode headerNode = Document.SelectSingleNode("/ia:Message/ia:Header", NSMgr); if (headerNode == null) { headerNode = Document.CreateElement("Header", NSMgr.LookupNamespace("ia")); if (Document.DocumentElement.HasChildNodes) { Document.DocumentElement.InsertBefore(headerNode, Document.DocumentElement.FirstChild); } else { Document.DocumentElement.AppendChild(headerNode); } } this.Header = new ILR.Header(headerNode, NSMgr); //Find the LearningProvider node XmlNode learningProviderNode = Document.SelectSingleNode("/ia:Message/ia:LearningProvider", NSMgr); //Find the Learner nodes XmlNodeList learnerNodes = Document.SelectNodes("/ia:Message/ia:Learner", NSMgr); //If we have no LearningProvider node create one in the correct place if (learningProviderNode == null) { learningProviderNode = Document.CreateElement("LearningProvider", NSMgr.LookupNamespace("ia")); if (learnerNodes.Count == 0) { Document.DocumentElement.AppendChild(learningProviderNode); } else { Document.DocumentElement.InsertBefore(learningProviderNode, learnerNodes.Item(0)); } } //Create a LearningProvider instance this.LearningProvider = new ILR.LearningProvider(learningProviderNode, NSMgr); //Create Learner instances for all of the learners in the XML foreach (XmlNode node in learnerNodes) { Learner newInstance = new Learner(node, NSMgr, IsFileImportLoadingRunning); newInstance.Message = this; newInstance.ResequenceAimSeqNumber(); newInstance.IsFileImportLoadingRunning = false; LearnerList.Add(newInstance); Log("Message", "Load", String.Format("Add Leaerner {0} of {1} - {2}", LearnerList.Count, learnerNodes.Count, newInstance.LearnRefNumber)); } //Find the LearnerDestinationandProgression nodes XmlNodeList learnerDestinationandProgressionNodes = Document.SelectNodes("/ia:Message/ia:LearnerDestinationandProgression", NSMgr); //Create LearnerDestinationandProgression instances for all of the LearnerDestinationandProgressions in the XML foreach (XmlNode node in learnerDestinationandProgressionNodes) { LearnerDestinationandProgression newLDP = new LearnerDestinationandProgression(node, NSMgr); newLDP.Message = this; LearnerDestinationandProgressionList.Add(newLDP); Log("Message", "Load", String.Format("Add LDP {0} of {1} - {2}", LearnerDestinationandProgressionList.Count, learnerDestinationandProgressionNodes.Count, newLDP.LearnRefNumber)); } //foreach (Learner l in LearnerList) //{ // foreach (LearningDelivery ld in l.LearningDeliveryList) // { // ld.IsImportRunning = false; // } // l.IsFileImportLoadingRunning = false; //} IsFileImportLoadingRunning = false; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public override void ExportCpp(ref StreamWriter writer) { WriteCommentDivider(ref writer); writer.Write("\n#include <string>\n"); writer.Write("\n#include <unordered_set>\n\n"); base.ExportCpp(ref writer); writer.Write("\n"); // // glew::wgl::Initialise // writer.Write("bool glew::wgl::s_initialised = false;\n\n"); writer.Write("glew::wgl::DeviceConfig glew::wgl::s_deviceConfig;\n\n"); WriteCommentDivider(ref writer); writer.Write("\nvoid glew::wgl::Initialise ()\n{\n"); writer.Write(" memset (&s_deviceConfig, 0, sizeof (s_deviceConfig));\n\n"); writer.Write(@" // // Determine current driver's feature reporting. // s_deviceConfig.m_featureSupported [GLEW_WGL_VERSION_1_0] = true; // // Evaluate extension support. // std::unordered_set <std::string> supportedExtensions; const unsigned char *wglExtensions = NULL; PFNWGLGETEXTENSIONSSTRINGARBPROC _wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress (""wglGetExtensionsStringARB""); PFNWGLGETEXTENSIONSSTRINGEXTPROC _wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress (""wglGetExtensionsStringEXT""); if (_wglGetExtensionsStringEXT != NULL) { wglExtensions = (const unsigned char*) _wglGetExtensionsStringEXT (); } else if (_wglGetExtensionsStringARB != NULL) { wglExtensions = (const unsigned char*) _wglGetExtensionsStringARB (wglGetCurrentDC()); } if (!wglExtensions) { wglExtensions = (const unsigned char*) """"; // Protect against some drivers will happily pass back NULL. } const size_t wglExtensionsLen = strlen ((const char *) wglExtensions); if (wglExtensionsLen) { unsigned char *thisExtStart = (unsigned char *) wglExtensions; unsigned char *thisExtEnd = NULL; char thisExtBuffer [128]; memset (thisExtBuffer, 0, sizeof (thisExtBuffer)); do { const char * seperator = strchr ((const char *) thisExtStart, ' '); if (seperator) { const size_t len = (((uintptr_t) seperator - (uintptr_t) thisExtStart) / sizeof (unsigned char)); #if _WIN32 strncpy_s (thisExtBuffer, 128, (const char *)thisExtStart, len); #else strncpy (thisExtBuffer, (const char *)thisExtStart, len); #endif thisExtBuffer [GLEW_MIN (len, 127)] = '\0'; thisExtEnd = (unsigned char *) seperator + 1; // skip tab character } else { const size_t len = strlen ((const char *) thisExtStart); #if _WIN32 strncpy_s (thisExtBuffer, 128, (const char *)thisExtStart, len); #else strncpy (thisExtBuffer, (const char *)thisExtStart, len); #endif thisExtBuffer [GLEW_MIN (len + 1, 127)] = '\0'; thisExtEnd = NULL; } std::string thisExt (thisExtBuffer); if (supportedExtensions.find (thisExt) == supportedExtensions.end ()) { supportedExtensions.insert (thisExt); } thisExtStart = thisExtEnd; } while ((thisExtStart && *thisExtStart != '\0') && (thisExtEnd && *thisExtEnd != '\0')); } "); foreach (var keypair in m_extensionNodesLookup) { writer.Write(string.Format(" s_deviceConfig.m_featureSupported [GLEW_{0}] = (supportedExtensions.find (\"{0}\") != supportedExtensions.end ());\n", keypair.Key)); } writer.Write("\n"); // // Collate feature and extension nodes together; as this can signifantly improve code re-use later. // Dictionary <string, XmlNode> featureAndExtensionNodes = new Dictionary <string, XmlNode> (); foreach (var keypair in m_featureNodesLookup) { if (!featureAndExtensionNodes.ContainsKey(keypair.Key)) { featureAndExtensionNodes.Add(keypair.Key, keypair.Value); } } foreach (var keypair in m_extensionNodesLookup) { if (!featureAndExtensionNodes.ContainsKey(keypair.Key)) { featureAndExtensionNodes.Add(keypair.Key, keypair.Value); } } if (featureAndExtensionNodes.Count > 0) { HashSet <string> definedPrototypes = new HashSet <string> (); Dictionary <string, HashSet <string> > featureBasedPrototypes = new Dictionary <string, HashSet <string> > (); foreach (var keypair in featureAndExtensionNodes) { XmlNode featureNode = keypair.Value; string api = m_api [0]; { XmlNode featureApiNode = featureNode.Attributes.GetNamedItem("api"); if (featureApiNode != null) { api = featureApiNode.Value; } } // // Multiple <require> tags can be nested in a feature/extension definition. It's possible for these to also be api specific. // XmlNodeList requireNodes = featureNode.SelectNodes("require"); if (requireNodes.Count == 0) { continue; } foreach (XmlNode requireNode in requireNodes) { XmlNode requireApiNode = requireNode.Attributes.GetNamedItem("api"); if (requireApiNode != null) { api = requireApiNode.Value; } if (!IsApiSupported(api)) { continue; // Skip non-supported APIs. } // // Evaluate whether this feature is part of the 'base spec'. // XmlNode featureNumberNode = featureNode.Attributes.GetNamedItem("number"); bool baseSpecFeatureSet = false; if (featureNumberNode != null) { float version = m_apiBaseSpecVersion [api]; if (float.TryParse(featureNumberNode.Value, out version)) { baseSpecFeatureSet = version <= m_apiBaseSpecVersion [api]; } } // // Export code for seeding available function/command addresses. // XmlNodeList requireCommandNodes = requireNode.SelectNodes("command"); if (requireCommandNodes.Count == 0) { continue; } HashSet <string> requiredCommands; if (!featureBasedPrototypes.TryGetValue(keypair.Key, out requiredCommands)) { requiredCommands = new HashSet <string> (); } foreach (XmlNode commandNode in requireCommandNodes) { string command = commandNode.Attributes ["name"].Value; if (definedPrototypes.Contains(command)) { continue; } definedPrototypes.Add(command); if (baseSpecFeatureSet) { continue; // Skip any base spec versions. } requiredCommands.Add(command); } featureBasedPrototypes [keypair.Key] = requiredCommands; } } // // Output condensed feature organised prototypes. // if (featureBasedPrototypes.Count > 0) { foreach (var keypair in featureBasedPrototypes) { if (keypair.Value.Count == 0) { continue; } writer.Write(string.Format(" // {0}\n", keypair.Key)); writer.Write(string.Format(" if (s_deviceConfig.m_featureSupported [GLEW_{0}])\n {{\n", keypair.Key)); foreach (string command in keypair.Value) { string mangedFunctionPointer = string.Format("PFN{0}PROC", command.ToUpperInvariant()); writer.Write(string.Format(" s_deviceConfig.m_{0} = ({1}) glewGetProcAddress (\"{0}\");\n", command, mangedFunctionPointer)); } writer.Write(" }\n\n"); } } } writer.Write(" s_initialised = true;\n"); writer.Write("}\n\n"); WriteCommentDivider(ref writer); // // glew::wgl::Deinitialise // writer.Write("\nvoid glew::wgl::Deinitialise ()\n{\n"); writer.Write(" s_initialised = false;\n"); writer.Write("}\n\n"); WriteCommentDivider(ref writer); }
private XmlDocument ProcessRetrieveDocumentSetResponse(XmlDocument xmlDocRequest, out StringDictionary atnaParametersValue) { XmlDocument xmlDocResponse = null; RetrieveDocumentSet objDocumentMetadata = null; RepositoryLogic repositoryLogic = null; List <RetrieveDocumentSet> lstRetrieveDocumentSet = null; RetrieveDocumentSet objRetrieveDocumentSet = null; XmlElement eltRoot = null; XmlNodeList nodeListDocumentRequest = null; XmlNode node = null; string documentEntryUUIDs = string.Empty; string eventOutomeIndicator = "0"; atnaParametersValue = new StringDictionary(); try { repositoryLogic = new RepositoryLogic(); lstRetrieveDocumentSet = new List <RetrieveDocumentSet>(); //Root Element eltRoot = xmlDocRequest.DocumentElement; nodeListDocumentRequest = eltRoot.SelectNodes(".//*[local-name()='DocumentRequest']"); foreach (XmlNode nodeDocumentRequest in nodeListDocumentRequest) { objRetrieveDocumentSet = new RetrieveDocumentSet(); if (nodeDocumentRequest.HasChildNodes) { node = nodeDocumentRequest.SelectSingleNode(".//*[local-name()='HomeCommunityId']"); if (node != null) { objRetrieveDocumentSet.HomeCommunityID = node.InnerText; } node = nodeDocumentRequest.SelectSingleNode(".//*[local-name()='RepositoryUniqueId']"); if (node != null) { objRetrieveDocumentSet.RepositoryUniqueID = node.InnerText; } node = nodeDocumentRequest.SelectSingleNode(".//*[local-name()='DocumentUniqueId']"); if (node != null) { objRetrieveDocumentSet.DocumentID = node.InnerText; } //Used for ATNA Logging if (string.IsNullOrEmpty(documentEntryUUIDs)) { documentEntryUUIDs = objRetrieveDocumentSet.DocumentID; } else { documentEntryUUIDs += ", " + objRetrieveDocumentSet.DocumentID; } //CP - No Validation required for RepositoryUniqueID //objRetrieveDocumentSet.IsRepositoryUniqueIDExsists = IsRepositoryIDExists(objRetrieveDocumentSet.RepositoryUniqueID); objDocumentMetadata = GetDocumentRepositoryMetaData(objRetrieveDocumentSet.DocumentID); objRetrieveDocumentSet.ContentID = objDocumentMetadata.ContentID; objRetrieveDocumentSet.MimeType = objDocumentMetadata.MimeType; if (objRetrieveDocumentSet.ContentID > 0) { objRetrieveDocumentSet.Content = SQLServerStorageService.RetreiveDocument(objRetrieveDocumentSet.ContentID.ToString()); } lstRetrieveDocumentSet.Add(objRetrieveDocumentSet); } } //ATNA atnaParametersValue.Add("$DocumentEntry.UUID$", documentEntryUUIDs); xmlDocResponse = GenerateTotalRetrieveDocument(); int contentCount = 0; for (int i = 0; i < lstRetrieveDocumentSet.Count; i++) { if (lstRetrieveDocumentSet[i].ContentID > 0) { contentCount++; } } if (contentCount == 0) { XmlElement docReosponseRootElement = xmlDocResponse.DocumentElement; XmlElement xEleRegErrList = xmlDocResponse.CreateElement("tns:RegistryResponse", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); XmlAttribute xAttStatus = xmlDocResponse.CreateAttribute("status"); xAttStatus.Value = GlobalValues.CONST_RESPONSE_STATUS_TYPE_FAILURE; xEleRegErrList.Attributes.Append(xAttStatus); XmlAttribute xAttXmlNSrs = xmlDocResponse.CreateAttribute("xmlns:tns"); xAttXmlNSrs.Value = "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"; xEleRegErrList.Attributes.Append(xAttXmlNSrs); XmlAttribute xAttXmlNS = xmlDocResponse.CreateAttribute("xmlns:rim"); xAttXmlNS.Value = GlobalValues.CONST_XML_NAMESPACE_x; xEleRegErrList.Attributes.Append(xAttXmlNS); XmlElement xEleRegErrList1 = xmlDocResponse.CreateElement("tns:RegistryErrorList", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); XmlAttribute attribhighestSeverity = xmlDocResponse.CreateAttribute("highestSeverity"); attribhighestSeverity.Value = "Highest SeverityURI"; xEleRegErrList1.Attributes.Append(attribhighestSeverity); for (int loop = 0; loop < lstRetrieveDocumentSet.Count; loop++) { XmlElement xEleRegErr = xmlDocResponse.CreateElement("tns:RegistryError", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); XmlAttribute xAttcodeContext = xmlDocResponse.CreateAttribute("codeContext"); xAttcodeContext.Value = GlobalValues.CONST_ERROR_CODE_XDSUnknownRepositoryUniqueID; xEleRegErr.Attributes.Append(xAttcodeContext); XmlAttribute xAttErrorCode = xmlDocResponse.CreateAttribute("errorCode"); xAttErrorCode.Value = string.Format("XDSDocumentEntry {0} exists in metadata with no corresponding attached document", lstRetrieveDocumentSet[loop].DocumentID); xEleRegErr.Attributes.Append(xAttErrorCode); XmlAttribute xAttSeverity = xmlDocResponse.CreateAttribute("severity"); xAttSeverity.Value = "Error"; xEleRegErr.Attributes.Append(xAttSeverity); XmlAttribute xAttLocation = xmlDocResponse.CreateAttribute("location"); xAttLocation.Value = lstRetrieveDocumentSet[loop].DocumentID; xEleRegErr.Attributes.Append(xAttLocation); xEleRegErrList1.AppendChild(xEleRegErr); } xEleRegErrList.AppendChild(xEleRegErrList1); docReosponseRootElement.AppendChild(xEleRegErrList); //ATNA Event Outcome Indicator eventOutomeIndicator = "8"; //Failure } if (contentCount < lstRetrieveDocumentSet.Count && contentCount > 0) { //Partial Error XmlElement rootElement = xmlDocResponse.DocumentElement; XmlElement xEleRegErrList = xmlDocResponse.CreateElement("tns:RegistryResponse", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); XmlAttribute xAttStatus = xmlDocResponse.CreateAttribute("status"); xAttStatus.Value = GlobalValues.CONST_RESPONSE_STATUS_TYPE_PARTIALSUCCESS; xEleRegErrList.Attributes.Append(xAttStatus); XmlAttribute xAttXmlNSrs = xmlDocResponse.CreateAttribute("xmlns:tns"); xAttXmlNSrs.Value = "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"; xEleRegErrList.Attributes.Append(xAttXmlNSrs); XmlAttribute xAttXmlNS = xmlDocResponse.CreateAttribute("xmlns:rim"); xAttXmlNS.Value = GlobalValues.CONST_XML_NAMESPACE_x; xEleRegErrList.Attributes.Append(xAttXmlNS); XmlElement xEleRegErrList1 = xmlDocResponse.CreateElement("tns:RegistryErrorList", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); XmlAttribute attribhighestSeverity = xmlDocResponse.CreateAttribute("highestSeverity"); attribhighestSeverity.Value = "Highest SeverityURI"; xEleRegErrList1.Attributes.Append(attribhighestSeverity); for (int loop = 0; loop < lstRetrieveDocumentSet.Count; loop++) { //Rep False || ContentID < 1 //if(Rep == false) // //else // ////CP - No Validation required for RepositoryUniqueId #region "CP - No Validation required for RepositoryUniqueId" //if (lstRetrieveDocumentSet[loop].IsRepositoryUniqueIDExsists == false) //{ // //RepositoryUniqueID not available // XmlElement xEleRegErr = xmlDocTotalRetrieveDocumentSet.CreateElement("tns:RegistryError", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); // XmlAttribute xAttcodeContext = xmlDocTotalRetrieveDocumentSet.CreateAttribute("codeContext"); // xAttcodeContext.Value = CONST_ERROR_CODE_XDSUnknownRepositoryUniqueID; // xEleRegErr.Attributes.Append(xAttcodeContext); // XmlAttribute xAttErrorCode = xmlDocTotalRetrieveDocumentSet.CreateAttribute("errorCode"); // xAttErrorCode.Value = "The repositoryUniqueId value could not be resolved to a valid document repository or the value does not match the repositoryUniqueId of the Document Repository"; // xEleRegErr.Attributes.Append(xAttErrorCode); // XmlAttribute xAttSeverity = xmlDocTotalRetrieveDocumentSet.CreateAttribute("severity"); // xAttSeverity.Value = "PartialSuccess"; // xEleRegErr.Attributes.Append(xAttSeverity); // XmlAttribute xAttLocation = xmlDocTotalRetrieveDocumentSet.CreateAttribute("location"); // xAttLocation.Value = lstRetrieveDocumentSet[loop].DocumentID; // xEleRegErr.Attributes.Append(xAttLocation); // xEleRegErrList1.AppendChild(xEleRegErr); // xEleRegErrList.AppendChild(xEleRegErrList1); //} #endregion if (lstRetrieveDocumentSet[loop].ContentID < 1) { //RepositoryUniqueID is available.....Content ID not available XmlElement xEleRegErr = xmlDocResponse.CreateElement("tns:RegistryError", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); XmlAttribute xAttcodeContext = xmlDocResponse.CreateAttribute("codeContext"); xAttcodeContext.Value = GlobalValues.CONST_ERROR_CODE_XDSRepositoryError; xEleRegErr.Attributes.Append(xAttcodeContext); XmlAttribute xAttErrorCode = xmlDocResponse.CreateAttribute("errorCode"); xAttErrorCode.Value = string.Format("XDSDocumentEntry {0} does not exists.", lstRetrieveDocumentSet[loop].DocumentID); xEleRegErr.Attributes.Append(xAttErrorCode); XmlAttribute xAttSeverity = xmlDocResponse.CreateAttribute("severity"); xAttSeverity.Value = "Error"; xEleRegErr.Attributes.Append(xAttSeverity); XmlAttribute xAttLocation = xmlDocResponse.CreateAttribute("location"); xAttLocation.Value = lstRetrieveDocumentSet[loop].DocumentID; xEleRegErr.Attributes.Append(xAttLocation); xEleRegErrList1.AppendChild(xEleRegErr); xEleRegErrList.AppendChild(xEleRegErrList1); } else { //Success xmlDocResponse = repositoryLogic.GenerateContentDocument(xmlDocResponse, lstRetrieveDocumentSet[loop]); } } rootElement.AppendChild(xEleRegErrList); //ATNA Event Outcome Indicator eventOutomeIndicator = "4"; //Partial Success } else if (contentCount == lstRetrieveDocumentSet.Count) { //Success XmlElement rootElement = xmlDocResponse.DocumentElement; XmlElement registryResponseElement = xmlDocResponse.CreateElement("tns:RegistryResponse", @"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"); //status registryResponseElement.Attributes.Append(xmlDocResponse.CreateAttribute("status")); registryResponseElement.Attributes["status"].Value = GlobalValues.CONST_RESPONSE_STATUS_TYPE_SUCCESS; //xmlns:tns registryResponseElement.Attributes.Append(xmlDocResponse.CreateAttribute("xmlns:tns")); registryResponseElement.Attributes["xmlns:tns"].Value = "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"; //xmlns:rim registryResponseElement.Attributes.Append(xmlDocResponse.CreateAttribute("xmlns:rim")); registryResponseElement.Attributes["xmlns:rim"].Value = GlobalValues.CONST_XML_NAMESPACE_x; //Appending Registry Response Element rootElement.AppendChild(registryResponseElement); for (int i = 0; i < lstRetrieveDocumentSet.Count; i++) { xmlDocResponse = repositoryLogic.GenerateContentDocument(xmlDocResponse, lstRetrieveDocumentSet[i]); } //ATNA Event Outcome Indicator eventOutomeIndicator = "0"; //Success } //xmlDocTotalRetrieveDocumentSet = GenerateContentDocument(xmlDocTotalRetrieveDocumentSet, lstDocEntries); } catch (Exception ex) { throw ex; } //msgRetrieveDocumentSetResponse = Message.CreateMessage(input.Headers.MessageVersion, CONST_ACTION_RETRIEVEDOCSETRESPONSE, new XmlNodeReader(xmlDocTotalRetrieveDocumentSet)); //ATNA atnaParametersValue.Add("$EventIdentification.EventOutcomeIndicator$", eventOutomeIndicator); //return msgRetrieveDocumentSetResponse; return(xmlDocResponse); }
public DataTable GetSurveyDetails(string surveyName, DateTime?startDate, DateTime?endDate) { DataTable returnValue = new DataTable(surveyName); string surveyPath = GetSurveyPath(surveyName); XDocument surveyDefinition = XDocument.Load(surveyPath); XmlDocument xml = new XmlDocument(); //var results; Dictionary <string, string> columns = new Dictionary <string, string>(); returnValue.Columns.Add("Date"); using (SurveyInformationDataContext repository = SurveyDataSource.ContactDataContext()) { var results = (from survey in repository.Surveys where survey.FormName == surveyName && startDate < survey.DateCreated && survey.DateCreated < endDate select new { Date = survey.DateCreated, FormDate = XDocument.Parse(survey.FormData.ToString()) }); xml.Load(surveyPath); XmlNodeList nodes = xml.SelectNodes("//Option"); foreach (XmlNode node in nodes) { XmlAttribute type = node.Attributes["type"]; XmlAttribute id = node.Attributes["id"]; if (type != null && id != null) { string prefix; switch (type.Value) { case "name": case "email": case "company": case "phone": case "address": case "city": case "zip": case "website": prefix = "t"; break; case "usstates": case "states": case "allstates": case "usterritories": case "canadianprovinces": prefix = "dd"; break; default: prefix = ""; break; } string questionName = id.Value; columns.Add(questionName, prefix + questionName); returnValue.Columns.Add(questionName); XmlNodeList otherNodes = node.SelectNodes("Option[@type='other']"); foreach (XmlNode otherNode in otherNodes) { string value = otherNode.Attributes["value"] == null ? "" : otherNode.Attributes["value"].Value; questionName = value + "_other"; columns.Add(questionName, questionName); returnValue.Columns.Add(questionName); } } } foreach (var survey in results) { DataRow row = returnValue.NewRow(); row["Date"] = survey.Date.ToString(); foreach (KeyValuePair <string, string> column in columns) { string response = (from answer in survey.FormDate.Descendants(column.Value) select answer.Value.ToString()).FirstOrDefault <string>(); row[column.Key] = response; } returnValue.Rows.Add(row); } } return(returnValue); }
static void FindAndReplace(XmlNodeList nodes, string find, string replace) { foreach (XmlNode node in nodes) FindAndReplace(node, find, replace); }
private string AddClassImplementation(string style, string gradient) { XmlNode svg = null; XmlNode styleNode = null; XmlNodeList nodes = null; XmlDocumentFragment frag = null; string linearId = null; string classId = null; bool add = true; //Find main svg node svg = base.SelectSingleNode("//svg"); if (svg == null) { throw new SvgDocumentException("SVG Document node not found"); } //Find or create style node styleNode = svg.SelectSingleNode("./style"); if (styleNode == null) { throw new SvgDocumentException("SVG Document Style node not found"); } //See if we need to add the linear definition if (gradient != null && gradient != string.Empty) { linearId = GetExistingGradientId(gradient); if (linearId == "") { nodes = svg.SelectNodes("//linearGradient"); linearId = "lg" + (nodes.Count + 1).ToString(); frag = base.CreateDocumentFragment(); frag.InnerXml = gradient; frag.FirstChild.Attributes.GetNamedItem("id").InnerText = linearId; svg.AppendChild(frag); } style = style.Replace("url(#none)", "url(#" + linearId + ")"); } //See if the style exists or if we need to add it if (mOptimised) { classId = GetExistingClassId(styleNode, style); add = classId == ""; } //Create a new classid if (classId == "") { classId = CreateClassId(styleNode); } //Add the style to the style section cdata if (add) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); stringBuilder.Append("."); stringBuilder.Append(classId); stringBuilder.Append("{"); stringBuilder.Append(style); stringBuilder.Append("}"); AddCData(styleNode, stringBuilder.ToString()); } return(classId); }
public IImageProperty[] GetProperties(IPresentationImage image) { List <IImageProperty> properties = new List <IImageProperty>(); if (image == null || !(image is IImageSopProvider)) { return(properties.ToArray()); } ISopDataSource dataSource = ((IImageSopProvider)image).ImageSop.DataSource; try { XmlDocument document = ImagePropertiesSettings.Default.StandardImagePropertiesXml; if (document == null) { Platform.Log(LogLevel.Debug, "StandardImagePropertiesXml setting document is null."); document = LoadDocumentFromResources(); } XmlNodeList groupNodes = document.SelectNodes("//standard-image-properties/image-property-group"); if (groupNodes == null || groupNodes.Count == 0) { Platform.Log(LogLevel.Debug, "StandardImagePropertiesXml setting document is empty or incorrectly formatted."); document = LoadDocumentFromResources(); groupNodes = document.SelectNodes("//standard-image-properties/image-property-group"); } if (groupNodes == null || groupNodes.Count == 0) { Platform.Log(LogLevel.Debug, "StandardImagePropertiesXml setting document is empty or incorrectly formatted."); return(properties.ToArray()); } foreach (XmlElement groupNode in groupNodes) { string category = ""; XmlAttribute categoryAttribute = groupNode.Attributes["name"]; if (categoryAttribute != null) { category = LookupCategory(categoryAttribute.Value); } XmlNodeList propertyNodes = groupNode.SelectNodes("image-property"); if (propertyNodes == null) { Platform.Log(LogLevel.Debug, "image-property-group element does not define any image-property elements"); continue; } foreach (XmlElement propertyNode in propertyNodes) { string tagVariableName = null; XmlAttribute tagVariableNameAttribute = propertyNode.Attributes["tag-variable-name"]; if (tagVariableNameAttribute != null) { tagVariableName = tagVariableNameAttribute.Value; } if (String.IsNullOrEmpty(tagVariableName)) { Platform.Log(LogLevel.Debug, "tag-variable-name attribute is empty"); continue; } var tag = LookupDicomTag(tagVariableName); if (tag == null) { Platform.Log(LogLevel.Debug, "tag-variable-name doesn't match a valid DicomTag"); continue; } string tagName = null; XmlAttribute attribute = propertyNode.Attributes["label"]; if (attribute != null) { tagName = attribute.Value; } string description = null; attribute = propertyNode.Attributes["description"]; if (attribute != null) { description = attribute.Value; } string separator = null; attribute = propertyNode.Attributes["separator"]; if (attribute != null) { separator = attribute.Value; } try { ImageProperty property = ImageProperty.Create(dataSource[tag], category, tagName, description, separator); properties.Add(property); } catch (Exception e) { Platform.Log(LogLevel.Debug, e, "Failed to create image property '{0}'.", tagName); } } } } catch (Exception e) { Platform.Log(LogLevel.Debug, e, "Failed to read in image properties xml."); } return(properties.ToArray()); }
EnumerateXmlNodes ( String sUrl, String sXPath, Int32 iMaximumXmlNodes, Boolean bSkipMostPage1Errors, RequestStatistics oRequestStatistics ) { Debug.Assert(!String.IsNullOrEmpty(sUrl)); Debug.Assert(!String.IsNullOrEmpty(sXPath)); Debug.Assert(iMaximumXmlNodes > 0); Debug.Assert(oRequestStatistics != null); AssertValid(); // A maximum per-page value of 500 works for // flickr.contacts.getPublicList (maximum per_page = 1000) and // flickr.people.getPublicPhotos (maximum per_page = 500). Debug.Assert(sUrl.IndexOf("flickr.contacts.getPublicList") >= 0 || sUrl.IndexOf("flickr.people.getPublicPhotos") >= 0); Int32 iMaximumPerPage = Math.Min(500, iMaximumXmlNodes); Int32 iPage = 1; Int32 iXmlNodesEnumerated = 0; while (true) { String sUrlWithPagination = String.Format( "{0}{1}per_page={2}&page={3}" , sUrl, sUrl.IndexOf('?') == -1 ? '?' : '&', iMaximumPerPage, iPage ); XmlDocument oXmlDocument; try { oXmlDocument = GetXmlDocument(sUrlWithPagination, oRequestStatistics); } catch (Exception oException) { if (!HttpSocialNetworkUtil.ExceptionIsWebOrXml(oException)) { throw oException; } if (iPage > 1 || bSkipMostPage1Errors) { // Always skip errors on page 2 and above. yield break; } throw (oException); } XmlNodeList oXmlNodesThisPage = oXmlDocument.SelectNodes(sXPath, null); Int32 iXmlNodesThisPage = oXmlNodesThisPage.Count; if (iXmlNodesThisPage == 0) { yield break; } for (Int32 i = 0; i < iXmlNodesThisPage; i++) { yield return(oXmlNodesThisPage[i]); iXmlNodesEnumerated++; if (iXmlNodesEnumerated == iMaximumXmlNodes) { yield break; } } iPage++; // Get the next page... } }
public IBinaryDataList ConvertTo(byte[] input, StringBuilder targetShape, out ErrorResultTO errors) { errors = new ErrorResultTO(); var payload = Encoding.UTF8.GetString(input); IBinaryDataList result = null; // build shape if(targetShape == null) { errors.AddError("Null payload or shape"); } else { ErrorResultTO invokeErrors; result = _tu.TranslateShapeToObject(targetShape, false, out invokeErrors); errors.MergeErrors(invokeErrors); // populate the shape if(payload != string.Empty) { try { string toLoad = DataListUtil.StripCrap(payload); // clean up the rubbish ;) XmlDocument xDoc = new XmlDocument(); try { xDoc.LoadXml(toLoad); } catch { // Append new root tags ;) toLoad = "<root>" + toLoad + "</root>"; xDoc.LoadXml(toLoad); } if(!string.IsNullOrEmpty(toLoad)) { if(xDoc.DocumentElement != null) { XmlNodeList children = xDoc.DocumentElement.ChildNodes; IDictionary<string, int> indexCache = new Dictionary<string, int>(); IBinaryDataListEntry entry; string error; if(children.Count > 0 && !DataListUtil.IsMsXmlBugNode(children[0].Name)) { #region Process children // spin through each element in the XML foreach(XmlNode c in children) { var hasCorrectIoDirection = true; if(c.Attributes != null) { var columnIoDirectionAttribute = c.Attributes["ColumnIODirection"]; if(columnIoDirectionAttribute != null) { var columnIoDirectionValue = columnIoDirectionAttribute.Value; var hasCorrectIoDirectionFromAttribute = columnIoDirectionValue == enDev2ColumnArgumentDirection.Output.ToString() || columnIoDirectionValue == enDev2ColumnArgumentDirection.Both.ToString(); hasCorrectIoDirection = hasCorrectIoDirectionFromAttribute; } } if(DataListUtil.IsSystemTag(c.Name) && !hasCorrectIoDirection) { continue; } // scalars and recordset fetch if(result.TryGetEntry(c.Name, out entry, out error)) { if(entry.IsRecordset) { // fetch recordset index int fetchIdx; int idx = indexCache.TryGetValue(c.Name, out fetchIdx) ? fetchIdx : 1; // process recordset XmlNodeList nl = c.ChildNodes; foreach(XmlNode subc in nl) { entry.TryPutRecordItemAtIndex(Dev2BinaryDataListFactory.CreateBinaryItem(subc.InnerXml, c.Name, subc.Name, (idx + "")), idx, out error); if(!string.IsNullOrEmpty(error)) { errors.AddError(error); } } // update this recordset index indexCache[c.Name] = ++idx; } else { entry.TryPutScalar(Dev2BinaryDataListFactory.CreateBinaryItem(c.InnerXml, c.Name), out error); if(!string.IsNullOrEmpty(error)) { errors.AddError(error); } } } else { errors.AddError(error); } } #endregion } else { var c = xDoc.DocumentElement; if(result.TryGetEntry(c.Name, out entry, out error)) { entry.TryPutScalar(Dev2BinaryDataListFactory.CreateBinaryItem(c.InnerXml, c.Name), out error); if(!string.IsNullOrEmpty(error)) { errors.AddError(error); } } } } } } catch(Exception e) { // if use passed in empty input they only wanted the shape ;) if(input.Length > 0) { errors.AddError(e.Message); } } } } return result; }
static void DeprecateNodes (XmlDocument document, XmlNodeList nodes) { foreach (XmlNode node in nodes) DeprecateNode (document, node); }
public void Import(string FilenameToLoad) { Log("Message", "Import", String.Format("File : {0}", FilenameToLoad)); String InterlStoreFilename = this.Filename; //Instantiate a new document to hold the ILR data this.ILRFile = new XmlDocument(); //Get a namespace manager from the XML document NSMgr = new XmlNamespaceManager(ILRFile.NameTable); NSMgr.AddNamespace("ia", CurrentNameSpace); this.ILRFile.AppendChild(this.ILRFile.CreateElement("Message", NSMgr.LookupNamespace("ia"))); // Clear Old Learner and Old LearnerDestinationandProgression Records this.LearnerList.Clear(); this.LearnerDestinationandProgressionList.Clear(); Message importMessage = new Message(); System.IO.FileInfo fi = new System.IO.FileInfo(FilenameToLoad); if (fi.Name.Contains("-" + CurrentYear.ToString() + "-")) { Log("Message", "Import", String.Format("Current Year : {0}", CurrentYear)); this.Load(FilenameToLoad); } else if (fi.Name.Contains("-" + (CurrentYear - 101).ToString() + "-")) { Log("Message", "Import", String.Format("Load Previous Year ILR : {0}", (CurrentYear - 101))); importMessage.LoadPreviousYearILR(FilenameToLoad, _logFileName); XmlNode headerNode = this.ILRFile.SelectSingleNode("/ia:Message/ia:Header", NSMgr); if (headerNode == null) { headerNode = this.ILRFile.CreateElement("Header", NSMgr.LookupNamespace("ia")); } if (this.ILRFile.DocumentElement.HasChildNodes) { this.ILRFile.DocumentElement.InsertBefore(headerNode, this.ILRFile.DocumentElement.FirstChild); } else { this.ILRFile.DocumentElement.AppendChild(headerNode); } this.Header = new ILR.Header(headerNode, NSMgr); //Find the LearningProvider node XmlNode learningProviderNode = this.ILRFile.SelectSingleNode("/ia:Message/ia:LearningProvider", NSMgr); //Find the Learner nodes XmlNodeList learnerNodes = this.ILRFile.SelectNodes("/ia:Message/ia:Learner", NSMgr); //If we have no LearningProvider node create one in the correct place if (learningProviderNode == null) { learningProviderNode = this.ILRFile.CreateElement("LearningProvider", NSMgr.LookupNamespace("ia")); if (learnerNodes.Count == 0) { this.ILRFile.DocumentElement.AppendChild(learningProviderNode); } else { this.ILRFile.DocumentElement.InsertBefore(learningProviderNode, learnerNodes.Item(0)); } } this.LearningProvider = new ILR.LearningProvider(learningProviderNode, NSMgr); this.LearningProvider.UKPRN = importMessage.LearningProvider.UKPRN; var x = importMessage.LearnerList.Where(l => l.HasContinuingAims); var y = importMessage.LearnerDestinationandProgressionList.Where(ldp => ldp.HasCurrentDPOutcomes); importMessage = null; foreach (Learner learner in x) { try { XmlNode newNode = ILRFile.CreateElement("Learner", NSMgr.LookupNamespace("ia")); Learner newInstance = new Learner(learner, newNode, NSMgr); newInstance.Message = this; LearnerList.Add(newInstance); AppendToLastOfNodeNamed(newNode, newNode.Name); newInstance.ResequenceAimSeqNumber(); Log("Message", "Import", String.Format("Learner {0} : {0}", LearnerList.Count, newInstance.LearnRefNumber)); } catch (Exception el) { Log("Message", "Import", String.Format("Error Loading Learner : {0}", el.Message)); Console.WriteLine(String.Format("Learern Ref:{0}", learner.LearnRefNumber)); } } foreach (LearnerDestinationandProgression learnerDestinationandProgression in y) { XmlNode newNode = ILRFile.CreateElement("LearnerDestinationandProgression", NSMgr.LookupNamespace("ia")); LearnerDestinationandProgression newInstance = new LearnerDestinationandProgression(learnerDestinationandProgression, newNode, NSMgr); newInstance.Message = this; LearnerDestinationandProgressionList.Add(newInstance); AppendToLastOfNodeNamed(newNode, newNode.Name); Log("Message", "Import", String.Format("LearnerDestinationandProgressionList {0} : {0}", LearnerDestinationandProgressionList.Count, newInstance.LearnRefNumber)); } importMessage = null; } else { throw (new Exception("Unable to identify Year from filename. Confirm the file name matchesd the ILR Specification.")); } this.Filename = InterlStoreFilename; Save(); GC.Collect(); }
// Parse from raw XML (-xo switch to dark.exe) table format. // Fagile implementation that assumes that the format is as // in inspected xml files. private void ParseXml(string path) { XmlDocument doc = new XmlDocument(); doc.Load(path); // Get basic stuff { XmlNodeList rows = GetTable("ModuleSignature", doc).GetElementsByTagName("row"); XmlElement row = (XmlElement)rows[0]; XmlNodeList fields = row.GetElementsByTagName("field"); _moduleId = fields[0].InnerText; _moduleLanguage = fields[1].InnerText; _moduleVersion = fields[2].InnerText; } // Get information // Format in: http://msdn2.microsoft.com/en-us/library/aa372045.aspx // Article: "Summary Information Stream Property Set" { XmlNodeList rows = GetTable("_SummaryInformation", doc).GetElementsByTagName("row"); _mouleDescription = GetFieldData(rows, 2); _moduleComments = GetFieldData(rows, 6); _moduleManufacturer = GetFieldData(rows, 4); _moduleInstallerVersion = ""; _modulePlatforms = GetFieldData(rows, 7); } // Get properties { XmlNodeList rows = GetTable("ModuleConfiguration", doc).GetElementsByTagName("row"); foreach (XmlElement row in rows) { Properties prop = new Properties(); XmlNodeList fields = row.GetElementsByTagName("field"); prop._Id = fields[0].InnerText; string value = fields[1].InnerText; if (value == "0") { prop._Type = Properties.Types.Text; } else if (value == "1") { prop._Type = Properties.Types.Key; } else if (value == "2") { prop._Type = Properties.Types.Integer; } else { prop._Type = Properties.Types.Bitfield; } if ((null != fields[5].InnerText) && ("" != fields[5].InnerText)) { prop._Nullable = ((int.Parse(fields[5].InnerText) & 2) == 2); } prop._Name = fields[0].InnerText; prop._DefaultValue = fields[4].InnerText; prop._Value = fields[4].InnerText; prop._Description = fields[7].InnerText; // Remove the attributes if it exists, but preserve the value in the replacement { foreach (Properties existing in _moduleProperties) { if ((null != existing.Id) && (prop.Id == existing.Id)) { prop.Value = existing.Value; _moduleProperties.Remove(existing); break; } } } _moduleProperties.Add(prop); } } }
static void CheckReply(object sender, ElapsedEventArgs e) { string notify = "通知して"; string notnotify = "通知しないで"; try { var rateLimits = bot.token.Application.RateLimitStatus(); int remaining = rateLimits["statuses"]["/statuses/mentions_timeline"].Remaining; if (remaining > 0) { foreach (var status in bot.token.Statuses.MentionsTimeline()) { if (status.Text.Contains(notify)) { XmlDocument document = new XmlDocument(); List <string> InReplyToUsers = new List <string>(); try { document.Load(xmlfilename); foreach (XmlElement element in document.DocumentElement) { InReplyToUsers.Add(element.InnerText); } if (!InReplyToUsers.Contains(status.User.ScreenName)) { bot.token.Statuses.Update(new { status = "@" + status.User.ScreenName + Environment.NewLine + "通知リストに追加します。", in_reply_to_status_id = status.Id }); var xmlfile = XElement.Load("./" + xmlfilename); var user = new XElement("user", status.User.ScreenName); xmlfile.Add(user); xmlfile.Save("./" + xmlfilename); } } catch (FileNotFoundException) { XmlDocument writer = new XmlDocument(); XmlDeclaration declaration = writer.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement torepusers = writer.CreateElement("Users"); writer.AppendChild(declaration); writer.AppendChild(torepusers); writer.Save(xmlfilename); Console.WriteLine("ファイルが存在しなかったため、ファイルを作成しました。"); } } if (status.Text.Contains(notnotify)) { XmlDocument xml = new XmlDocument(); xml.Load(xmlfilename); XmlNodeList list = xml.GetElementsByTagName("user"); foreach (XmlNode xn in list) { if (xn.InnerText == status.User.ScreenName) { bot.token.Statuses.Update(new { status = "@" + status.User.ScreenName + Environment.NewLine + "通知リストから削除します。", in_reply_to_status_id = status.Id }); xn.RemoveAll(); break; } } xml.Save(xmlfilename); } break; } } else { Console.WriteLine("--- API切れにより取得に失敗しました。"); } } catch { Console.WriteLine("--- タイムアウトしました."); } }
protected void Page_Load(object sender, EventArgs e) { if (!base.IsPostBack) { try { SortedDictionary <string, object> m_values = new SortedDictionary <string, object>(); Stream s = base.Request.InputStream; byte[] buffer = new byte[1024]; StringBuilder builder = new StringBuilder(); int count; while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(Encoding.UTF8.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(builder.ToString()); XmlNode xmlNode = xmlDoc.FirstChild; XmlNodeList nodes = xmlNode.ChildNodes; foreach (XmlNode xn in nodes) { XmlElement xe = (XmlElement)xn; m_values[xe.Name] = xe.InnerText; } if (!(m_values["return_code"].ToString() != "SUCCESS")) { string out_trade_no = m_values["out_trade_no"].ToString(); string appid = m_values["appid"].ToString(); string mch_id = m_values["mch_id"].ToString(); string transaction_id = m_values["transaction_id"].ToString(); string nonce_str = m_values["nonce_str"].ToString(); string sign = m_values["sign"].ToString(); string time_end = m_values["time_end"].ToString(); string attach = m_values["attach"].ToString(); string[] sz = attach.Split(new char[] { ',' }); string type = sz[0]; string text = type; if (text != null) { if (text == "Membersrecharge") { Chain.BLL.MemRecharge bllMemRecharge = new Chain.BLL.MemRecharge(); DataSet ds = bllMemRecharge.GetList(string.Format(" RechargeAccount='{0}'", out_trade_no)); if (ds.Tables[0].Rows.Count > 0) { base.Response.Write(this.ToXml("SUCCESS", "")); base.Response.End(); } else { CheckOrder checkorder = new CheckOrder(); Sign signss = new Sign(); Chain.Model.SysParameter modelSysParameter = new Chain.BLL.SysParameter().GetModel(1); string ordertrackingsign = signss.OrderTrackingSign(appid, mch_id, nonce_str, out_trade_no, transaction_id, modelSysParameter.Api); XmlNode xmNode = checkorder.GetCheckOrder(appid, mch_id, transaction_id, out_trade_no, nonce_str, ordertrackingsign); string trade_state = xmNode["trade_state"].InnerText.ToUpper(); if (!(trade_state != "SUCCESS")) { int total_fee = Convert.ToInt32(sz[2]); int total_fees = Convert.ToInt32(m_values["total_fee"]); if (total_fee == total_fees) { text = type; if (text != null) { if (!(text == "Membersrecharge")) { if (text == "ShopMembersRecharge") { base.Response.Write(this.ToXml("SUCCESS", "")); base.Response.End(); } } else { this.Membersrecharge(sz[1], sz[2], sz[3], sz[4], out_trade_no, time_end); } } } } } } } } } catch (Exception) { } } }
/// <summary> /// Get all the templates in BackgroundTemplate.xml /// </summary> public void GetTemplates(ArrayList templates) { //Create XmlDocument and Load BackgroundTemplate.xml StreamReader sr = new StreamReader(this.m_BackgroundTemplateXmlPath); XmlDocument doc = new XmlDocument(); doc.Load(sr); string language = null; using (Synchronizer.Lock(m_ViewerStateModel.SyncRoot)) { language = m_ViewerStateModel.Language; } //Get all the BackgroundTemplate Nodes, and parse each template node XmlNodeList list = doc.GetElementsByTagName("BackgroundTemplate"); for (int i = 0; i < list.Count; i++) { BackgroundTemplate template = new BackgroundTemplate(language); XmlNode templateNode = list[i]; XmlAttribute temp; //Get the name of the BackgroundTemplate temp = templateNode.Attributes["name"]; if (temp != null) { template.Name = temp.Value; } //Get the chinese name temp = templateNode.Attributes["name.zh-CN"]; if (temp != null) { template.CNName = temp.Value; } //Get the spanish name temp = templateNode.Attributes["name.es-ES"]; if (temp != null) { template.ESName = temp.Value; } //Get the french name temp = templateNode.Attributes["name.fr-FR"]; if (temp != null) { template.FRName = temp.Value; } //Get the portuguese name temp = templateNode.Attributes["name.pt-BR"]; if (temp != null) { template.PTName = temp.Value; } //Get the width of the BackgroundTemplate temp = templateNode.Attributes["width"]; if (temp != null) { template.Width = Int32.Parse(temp.Value); } //Get the height of the BackgroundTemplate temp = templateNode.Attributes["height"]; if (temp != null) { template.Height = Int32.Parse(temp.Value); } //Get the childnode of PrimitivePens, BackgroundBrush, GeomrtryTransform, Geometry XmlNodeList childnodes = templateNode.ChildNodes; for (int j = 0; j < childnodes.Count; j++) { XmlNode subNode = childnodes[j]; switch (subNode.Name) { case "PrimitivePens": ParsePrimitivePens(subNode, template); break; case "BackgroundBrush": ParseBackgroundBrush(subNode, template); break; case "GeometryTransform": template.GeometryTransform = ParseGeometryTransform(subNode); break; case "Geometry": ParseGeometry(subNode, template.Geometry); break; } } templates.Add(template); } sr.Close(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Session["stuId"] != null) { string stuId = Session["stuId"].ToString(); stuNews1 = StudentInfoManager.Getstudentnews(stuId); StudentInfoManager.Showstudentnews1(stuNews1, lblstuName, lblstyle, imgphoto); if (lblstyle.Text == "活跃型+视觉型" || lblstyle.Text == "活跃型+言语型") { lbldata.Text = "视频"; } else if (lblstyle.Text == "沉思型+视觉型") { lbldata.Text = "图片"; } else if (lblstyle.Text == "沉思型+言语型") { lbldata.Text = "文字"; } else { Response.Redirect("../LearningStyleText.aspx"); } rbl1.SelectedValue = "1"; //再读一遍XML string Num = ""; //C#读取XML文件 http://www.cnblogs.com/xiaoxiangfeizi/archive/2011/08/07/2120807.html XmlDocument doc = new XmlDocument(); //使用的时候,首先声明一个XmlDocument对象,然后调用Load方法,从指定的路径加载XML文件 doc.Load(Server.MapPath("../XML/" + Session["stuId"].ToString() + ".xml")); //然后可以通过调用SelectSingleNode得到指定的结点,通过GetAttribute得到具体的属性值.参看下面的代码 // 得到根节点"学习建议" XmlNode xn = doc.SelectSingleNode("学习建议"); // 得到根节点的所有子节点 XmlNodeList xnl = xn.ChildNodes; foreach (XmlNode xn1 in xnl) { // 将节点转换为元素,便于得到节点的属性值 XmlElement xe = (XmlElement)xn1; // 得到Type和ISBN两个属性的属性值 Num = Num + xe.GetAttribute("类型").ToString() + ","; } if (Num == "") { lblsug.Text = lblstuName.Text + "同学,欢迎进入学习资料素材库!"; } else { lblsug.Text = lblstuName.Text + "同学,在上次测试中你需要复习知识点有:" + Num; } } else { Response.Redirect("../Login.aspx"); } } }
/// <summary> /// Performs actions based on the character's last loaded AppVersion attribute. /// </summary> private void LegacyShim() { //Unstored Cost and LP values prior to 5.190.2 nightlies. if (_objCharacter.LastSavedVersion <= new Version("5.190.0")) { XmlDocument objXmlDocument = XmlManager.Load("lifestyles.xml"); XmlNode objLifestyleQualityNode = GetNode() ?? objXmlDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + _strName + "\"]"); if (objLifestyleQualityNode == null) { List <ListItem> lstQualities = new List <ListItem>(); using (XmlNodeList xmlQualityList = objXmlDocument.SelectNodes("/chummer/qualities/quality")) if (xmlQualityList != null) { foreach (XmlNode xmlNode in xmlQualityList) { lstQualities.Add(new ListItem(xmlNode["id"]?.InnerText, xmlNode["translate"]?.InnerText ?? xmlNode["name"]?.InnerText)); } } frmSelectItem frmSelect = new frmSelectItem { GeneralItems = lstQualities, Description = LanguageManager.GetString("String_CannotFindLifestyleQuality", GlobalOptions.Language).Replace("{0}", _strName) }; frmSelect.ShowDialog(); if (frmSelect.DialogResult == DialogResult.Cancel) { return; } objLifestyleQualityNode = objXmlDocument.SelectSingleNode("/chummer/qualities/quality[id = \"" + frmSelect.SelectedItem + "\"]"); } int intTemp = 0; string strTemp = string.Empty; if (objLifestyleQualityNode.TryGetStringFieldQuickly("cost", ref strTemp)) { CostString = strTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("lp", ref intTemp)) { LP = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("areamaximum", ref intTemp)) { AreaMaximum = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("comfortsmaximum", ref intTemp)) { ComfortMaximum = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("securitymaximum", ref intTemp)) { SecurityMaximum = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("area", ref intTemp)) { Area = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("comforts", ref intTemp)) { Comfort = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("security", ref intTemp)) { Security = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("multiplier", ref intTemp)) { Multiplier = intTemp; } if (objLifestyleQualityNode.TryGetInt32FieldQuickly("multiplierbaseonly", ref intTemp)) { BaseMultiplier = intTemp; } } }
/// <summary> /// Creates an ASP.NET compatible strongly typed resource from a ResX file in ASP.NET. /// The class generated works only for Global Resources by calling GetGlobalResourceObject. /// /// This routine parses the raw ResX files since you can't easily get access to the active /// ResourceManager in an ASP.NET application since the assembly is dynamically named and not /// easily accessible. /// </summary> /// <param name="ResourceSetFileName"></param> /// <param name="Namespace"></param> /// <param name="FileName">Output filename for the CSharp class. If null no file is generated and only the class is returned</param> /// <returns></returns> public string CreateClassFromResXResource(string ResXFile, string Namespace, string Classname, string FileName) { XmlDocument Dom = new XmlDocument(); bool IsVb = IsFileVb(FileName); try { Dom.Load(ResXFile); } catch (Exception ex) { ErrorMessage = ex.Message; return(null); } string Indent = "\t\t"; StringBuilder sbClass = new StringBuilder(); CreateClassHeader(Classname, Namespace, IsVb, sbClass); XmlNodeList nodes = Dom.DocumentElement.SelectNodes("data"); foreach (XmlNode Node in nodes) { string value = Node.ChildNodes[0].InnerText; string resourceId = Node.Attributes["name"].Value; string varName = SafeVarName(resourceId); string typeName = null; if (Node.Attributes["type"] != null) { typeName = Node.Attributes["type"].Value; } if (!string.IsNullOrEmpty(typeName)) { // File based resources are formatted: filename;full type name string[] tokens = value.Split(';'); if (tokens.Length > 0) { // Grab the type and get the full name typeName = Type.GetType(tokens[1]).FullName; } } else { typeName = "System.String"; } // It's a string if (!IsVb) { sbClass.Append(Indent + "public static " + typeName + " " + varName + "\r\n" + Indent + "{\r\n"); sbClass.AppendFormat(Indent + "\tget {{ return ({2}) HttpContext.GetGlobalResourceObject(\"{0}\",\"{1}\"); }}\r\n", Classname, resourceId, typeName); sbClass.Append(Indent + "}\r\n\r\n"); } else { sbClass.Append(Indent + "Public Shared ReadOnly Property " + resourceId + "() as " + typeName + "\r\n"); sbClass.AppendFormat(Indent + "\tGet\r\n" + Indent + "\t\treturn CType( HttpContext.GetGlobalResourceObject(\"{0}\",\"{1}\"), {2})\r\n", Classname, resourceId, typeName); sbClass.Append(Indent + "\tEnd Get\r\n"); sbClass.Append(Indent + "End Property\r\n\r\n"); } } if (!IsVb) { sbClass.Append("\t}\r\n\r\n"); } else { sbClass.Append("End Class\r\n\r\n"); } if (!string.IsNullOrEmpty(FileName)) { string FileContent = CreateNameSpaceWrapper(Namespace, IsVb, sbClass.ToString(), true); File.WriteAllText(FileName, FileContent); return(FileContent); } return(sbClass.ToString()); }
private string resolveKYTXMLAndConvert(string field_id, string xml) { JObject joReturn = new JObject(); // 組出Data層 JArray jaData = new JArray(); joReturn.Add(new JProperty("data", jaData)); // 組出兩個起單屬性(一般或外掛) JArray jaType1 = new JArray(); jaData.Add(jaType1); // 組出一個一般表單的空結構 JObject joType1 = new JObject(); joType1.Add(new JProperty("formtype", "builtIn")); joType1.Add(new JProperty("formdata", new JObject())); jaType1.Add(joType1); // 組出外掛表單結構 JArray jaType2 = new JArray(); jaData.Add(jaType2); JObject joType2 = new JObject(); jaType2.Add(joType2); // 組出一個上傳檔案的空架構 JObject joFileUpload = new JObject(); jaType2.Add(joFileUpload); joFileUpload.Add(new JProperty("filedownload", "")); joFileUpload.Add(new JProperty("filename", "")); // 開始建立表單網頁物件結構 JObject joFormData = new JObject(); joType2.Add(new JProperty("formtype", "plugIn")); joType2.Add(new JProperty("formdata", joFormData)); if (!string.IsNullOrEmpty(field_id)) { XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(xml); XmlNodeList nodes = xdoc.SelectNodes("Form/FormFieldValue/FieldItem"); foreach (XmlNode _node in nodes) { XmlElement element = _node as XmlElement; string fieldId = element.GetAttribute("fieldId"); if (fieldId.Equals(field_id)) { // 表單物件結構 JArray jaFieldValue = new JArray(); joFormData.Add(new JProperty(fieldId, jaFieldValue)); JObject joHtmlObj = new JObject(); jaFieldValue.Add(joHtmlObj); string kytJson = element.InnerText; if (!string.IsNullOrEmpty(kytJson)) { JObject JoKyt = JObject.Parse(kytJson); foreach (var _jo in JoKyt) { JObject _joObjStruct = JObject.Parse(_jo.Value.ToString()); string fieldValue = _joObjStruct["FieldValue"].ToString(); if (IsBasee64Encoded(fieldValue)) // 判斷是GV { JArray jaGridView = new JArray(); joHtmlObj.Add(new JProperty(_jo.Key, jaGridView)); JObject joGV = new JObject(); jaGridView.Add(joGV); if (!string.IsNullOrEmpty(fieldValue)) { try { byte[] bytes = Convert.FromBase64String(fieldValue); using (MemoryStream ms = new MemoryStream(bytes)) { BinaryFormatter formatter = new BinaryFormatter(); DataTable dtGV = formatter.Deserialize(ms) as DataTable; if (dtGV.Rows.Count > 0) { joGV.Add(new JProperty("type", "detail")); for (int i = 0; i < dtGV.Rows.Count; i++) { DataRow dr = dtGV.Rows[i]; JArray _jaGV = new JArray(); joGV.Add((i + 1).ToString(), _jaGV); JObject _joGVObj = new JObject(); _jaGV.Add(_joGVObj); foreach (DataColumn dc in dtGV.Columns) { _joGVObj.Add(new JProperty(dc.ColumnName, dr[dc.ColumnName])); } } } } } catch (Exception ex) { DebugLog.Log(string.Format(@"WKFConvertToAFJSON.resolveKYTXMLAndConvert.ConvertToGVDataTable.Error:{0}", ex.Message)); } } } else // 不是GridView物件 { joHtmlObj.Add(new JProperty(_jo.Key, fieldValue)); } } } } } } return(joReturn.ToString()); }
private string GetExtensions(string scattendID) { string Extension = ""; // 沒東西,做新的給它 if (xmlRecordDict[scattendID] == "") { foreach (DataGridViewRow r in dataGridViewX1.Rows) { if ("" + r.Tag == scattendID) { XmlDocument doc = new XmlDocument(); XmlElement element_Rule = doc.CreateElement(string.Empty, "Rule", string.Empty); element_Rule.InnerXml = "" + r.Cells[8].Value;; XmlElement element_Extension = doc.CreateElement(string.Empty, "Extension", string.Empty); element_Extension.SetAttribute("Name", "DuplicatedLevelSubjectCalRule"); XmlElement element_Extensions = doc.CreateElement(string.Empty, "Extensions", string.Empty); element_Extension.AppendChild(element_Rule); element_Extensions.AppendChild(element_Extension); doc.AppendChild(element_Extensions); Extension = doc.OuterXml; } } } // 原本有東西 舊的保留 再另外加 else { foreach (DataGridViewRow r in dataGridViewX1.Rows) { if ("" + r.Tag == scattendID) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlRecordDict[scattendID]); XmlNodeList nodeList = doc.GetElementsByTagName("Rule"); // 第一次檢查 是沒有 Rule element 的 if (nodeList.Count == 0) { XmlElement element_Rule = doc.CreateElement(string.Empty, "Rule", string.Empty); element_Rule.InnerXml = "" + r.Cells[8].Value; XmlElement element_Extension = doc.CreateElement(string.Empty, "Extension", string.Empty); element_Extension.SetAttribute("Name", "DuplicatedLevelSubjectCalRule"); element_Extension.AppendChild(element_Rule); doc.DocumentElement.AppendChild(element_Extension); } else // 如果有的話 直接更新 { nodeList[0].InnerXml = "" + r.Cells[8].Value; } Extension = doc.OuterXml; } } } return(Extension); }
public void getmoyuAreaAndServer(string gamename, string areaname, string servername, ref string areaid, ref string serverid) { try { string url = "https://xmlserver.99.com/my/mycharge.xml?0.8311741468522764"; switch (gamename) { case "魔域": url = "https://xmlserver.99.com/my/mycharge.xml?0.8311741468522764"; break; case "魔域掉钱版": url = "https://xmlserver.99.com/my/Chsjmy.xml?0.5738079243209351"; break; case "魔域口袋版": url = "https://xmlserver.99.com/my/mysjcharge.xml?0.3160789587639954"; break; case "机战": url = "https://xmlserver.99.com//jz/jzcharge.xml?0.8663311481081863"; break; case "征服": url = "https://xmlserver.99.com/zf/zfcharge.xml?0.9778757448608422"; break; default: url = "https://xmlserver.99.com/my/mycharge.xml?0.8311741468522764"; break; } areaname = areaname.Replace('(', '(').Replace(')', ')'); //servername = servername.Replace('(', '(').Replace(')', ')'); Dictionary <string, string> dicArea = new Dictionary <string, string>(); Dictionary <string, List <Dictionary <string, string> > > dicServer = new Dictionary <string, List <Dictionary <string, string> > > (); CookieContainer coockie = new CookieContainer(); string result = PostAndGet.HttpGetString(url, "", ref coockie); XmlDocument docArea = new XmlDocument(); docArea.LoadXml(result); //加载Xml文件 XmlElement rootArea = docArea.DocumentElement; //获取根节点 XmlNodeList AreaNodes = rootArea.GetElementsByTagName("MainTable"); //获取area foreach (XmlNode node in AreaNodes) { //string Code = ((XmlElement)node).GetAttribute("Code"); //获取Code属性值 string key = ((XmlElement)node).GetElementsByTagName("key")[0].InnerText; string name = ((XmlElement)node).GetElementsByTagName("name")[0].InnerText; dicArea.Add(key, name); } XmlDocument docServer = new XmlDocument(); docServer.LoadXml(result); //加载Xml文件 XmlElement rootServer = docServer.DocumentElement; //获取根节点 XmlNodeList ServerNodes = rootServer.GetElementsByTagName("SubTable"); //获取sever foreach (XmlNode node in ServerNodes) { string key = ((XmlElement)node).GetElementsByTagName("key")[0].InnerText; string name = ((XmlElement)node).GetElementsByTagName("name")[0].InnerText; string ParentKey = ((XmlElement)node).GetElementsByTagName("ParentKey")[0].InnerText; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add(key, name); bool isNew = true; foreach (string serverkey in dicServer.Keys) { if (ParentKey == serverkey) { dicServer[serverkey].Add(dic); isNew = false; break; } } if (isNew) { List <Dictionary <string, string> > lst = new List <Dictionary <string, string> > (); lst.Add(dic); dicServer.Add(ParentKey, lst); } } if (!string.IsNullOrEmpty(areaname)) { foreach (string item in dicArea.Keys) { if (dicArea[item] == areaname) { areaid = item; break; } } } if (!string.IsNullOrEmpty(areaname) && !string.IsNullOrEmpty(servername)) { foreach (string key in dicArea.Keys) { if (dicArea[key] == areaname) { foreach (string parentKey in dicServer.Keys) { if (parentKey == key) { foreach (Dictionary <string, string> dic in dicServer[parentKey]) { foreach (string serverkey in dic.Keys) { if (servername == dic[serverkey]) { serverid = serverkey; break; } } } } } } } } } catch (Exception ex) { WriteLog.Write("方法:getmoyuAreaAndServer,异常:" + ex.Message, LogPathFile.Exception.ToString()); throw; } }
private void ParseMethod() { XmlNodeList children = node.ChildNodes; foreach (XmlNode child in children) { if (child.Name == "ownedParameters") { ParseArguments(child.ChildNodes); } else if (child.Name == "preconditionsInternal") { XmlNode constraintNode = child.FirstChild; foreach (XmlNode node in constraintNode.ChildNodes) { if (node.Name == "specification") { preconditionNode = node.FirstChild.Attributes.GetNamedItem("value"); List <string> split = ConditionSplit(preconditionNode.InnerText); foreach (string s in split) { Preconditions.Add(new OclCondition(s)); } break; } } } else if (child.Name == "postconditionsInternal") { XmlNode constraintNode = child.FirstChild; foreach (XmlNode node in constraintNode.ChildNodes) { if (node.Name == "specification") { postconditionNode = node.FirstChild.Attributes.GetNamedItem("value"); List <string> split = ConditionSplit(postconditionNode.InnerText); foreach (string s in split) { Console.WriteLine(s); Postconditions.Add(new LinkedOclCondition(Preconditions, s)); } break; } } } } XmlDocument doc = node.OwnerDocument; // Create nodes in place if they don't already exist. if (preconditionNode == null) { preconditionNode = doc.CreateElement("preconditionsInternal"); node.AppendChild(preconditionNode); preconditionNode = PopulateConstraintNode(preconditionNode); } if (postconditionNode == null) { postconditionNode = doc.CreateElement("postconditionsInternal"); node.AppendChild(postconditionNode); postconditionNode = PopulateConstraintNode(postconditionNode); } }
/// <summary> /// 初始化 系统启动时的语言包、风格 /// </summary> public static void InitStartedAppliactionData() { string LStrXMLFileFolder = string.Empty; string LStrXmlFileName = string.Empty; string LStrSupportAllLanguagesText = string.Empty; #region 初始化表 GDataTableSupportLanguages = new DataTable(); GDataTableSupportStyles = new DataTable(); GDataTableNecessaryLanguages = new DataTable(); GDataTableConvertData = new DataTable(); GDataTableSupportLanguages.Columns.Add("C001", typeof(string)); GDataTableSupportLanguages.Columns.Add("C002", typeof(string)); GDataTableSupportLanguages.Columns.Add("C003", typeof(int)); GDataTableSupportLanguages.Columns.Add("C004", typeof(string)); GDataTableSupportLanguages.Columns.Add("C005", typeof(string)); GDataTableSupportStyles.Columns.Add("C001", typeof(string)); GDataTableSupportStyles.Columns.Add("C002", typeof(string)); GDataTableNecessaryLanguages.Columns.Add("C001", typeof(string)); GDataTableNecessaryLanguages.Columns.Add("C002", typeof(string)); GDataTableNecessaryLanguages.Columns.Add("C003", typeof(string)); GDataTableNecessaryLanguages.Columns.Add("C004", typeof(string)); GDataTableNecessaryLanguages.Columns.Add("C005", typeof(string)); GDataTableConvertData.Columns.Add("DataSource", typeof(string)); GDataTableConvertData.Columns.Add("DataConverted", typeof(string)); #endregion #region 加载配置文件 LStrXMLFileFolder = System.IO.Path.Combine(App.GStrApplicationDirectory, "Languages"); LStrSupportAllLanguagesText = System.IO.Path.Combine(LStrXMLFileFolder, "SAllLanguages.txt"); string[] LStrArrayLangInfo = File.ReadAllLines(LStrSupportAllLanguagesText, Encoding.UTF8); foreach (string LStrSingleLang in LStrArrayLangInfo) { string[] LStrArraySingleLanguage = LStrSingleLang.Split('|'); if (LStrArraySingleLanguage[1] == GStrLoginUserCurrentLanguageID) { GStrLoginUserCurrentLanguageID = LStrArraySingleLanguage[0]; break; } } LStrXmlFileName = System.IO.Path.Combine(LStrXMLFileFolder, "S" + GStrLoginUserCurrentLanguageID + ".xml"); if (!File.Exists(LStrXmlFileName)) { LStrXmlFileName = System.IO.Path.Combine(LStrXMLFileFolder, "S2052.xml"); App.GStrLoginUserCurrentLanguageID = "2052"; } XmlDocument LXmlDocument = new XmlDocument(); LXmlDocument.Load(LStrXmlFileName); #endregion #region 读取支持的语言列表 XmlNode LXMLNodeSupportLanguages = LXmlDocument.SelectSingleNode("UMPTools").SelectSingleNode("SupportLanguages"); XmlNodeList LXmlNodeSupportLanguages = LXMLNodeSupportLanguages.ChildNodes; foreach (XmlNode LXmlNodeSingleLanguage in LXmlNodeSupportLanguages) { DataRow LDataRow = GDataTableSupportLanguages.NewRow(); LDataRow.BeginEdit(); LDataRow["C001"] = LXmlNodeSingleLanguage.Attributes["C001"].Value; LDataRow["C002"] = LXmlNodeSingleLanguage.Attributes["C002"].Value; LDataRow["C003"] = int.Parse(LXmlNodeSingleLanguage.Attributes["C003"].Value); LDataRow["C004"] = LXmlNodeSingleLanguage.Attributes["C004"].Value; LDataRow["C005"] = LXmlNodeSingleLanguage.Attributes["C005"].Value; LDataRow.EndEdit(); GDataTableSupportLanguages.Rows.Add(LDataRow); } #endregion #region 读取支持的Style XmlNode LXMLNodeSupportStyle = LXmlDocument.SelectSingleNode("UMPTools").SelectSingleNode("SupportStyle"); XmlNodeList LXmlNodeSupportStyles = LXMLNodeSupportStyle.ChildNodes; foreach (XmlNode LXmlNodeSingleStyle in LXmlNodeSupportStyles) { DataRow LDataRow = GDataTableSupportStyles.NewRow(); LDataRow.BeginEdit(); LDataRow["C001"] = LXmlNodeSingleStyle.Attributes["C001"].Value; LDataRow["C002"] = LXmlNodeSingleStyle.Attributes["C002"].Value; LDataRow.EndEdit(); GDataTableSupportStyles.Rows.Add(LDataRow); } #endregion #region 读取语言包 XmlNode LXMLNodeLanguages = LXmlDocument.SelectSingleNode("UMPTools").SelectSingleNode("Languages"); XmlNodeList LXmlNodeLanguages = LXMLNodeLanguages.ChildNodes; foreach (XmlNode LXmlNodeSingleLanguageItem in LXmlNodeLanguages) { if (LXmlNodeSingleLanguageItem.NodeType == XmlNodeType.Comment) { continue; } DataRow LDataRow = GDataTableNecessaryLanguages.NewRow(); LDataRow.BeginEdit(); LDataRow["C001"] = LXmlNodeSingleLanguageItem.Attributes["C001"].Value; LDataRow["C002"] = LXmlNodeSingleLanguageItem.Attributes["C002"].Value; LDataRow["C003"] = LXmlNodeSingleLanguageItem.Attributes["C003"].Value; LDataRow["C004"] = LXmlNodeSingleLanguageItem.Attributes["C004"].Value; LDataRow["C005"] = LXmlNodeSingleLanguageItem.Attributes["C005"].Value; LDataRow.EndEdit(); GDataTableNecessaryLanguages.Rows.Add(LDataRow); } #endregion #region 读取数据转换信息 XmlNode LXMLDataConvert = LXmlDocument.SelectSingleNode("UMPTools").SelectSingleNode("DataConvert"); XmlNodeList LXmlNodeDataConverts = LXMLDataConvert.ChildNodes; foreach (XmlNode LXmlNodeSingleDataConvert in LXmlNodeDataConverts) { DataRow LDataRow = GDataTableConvertData.NewRow(); LDataRow.BeginEdit(); LDataRow["DataSource"] = LXmlNodeSingleDataConvert.Attributes["DataSource"].Value; LDataRow["DataConverted"] = LXmlNodeSingleDataConvert.Attributes["DataConverted"].Value; LDataRow.EndEdit(); GDataTableConvertData.Rows.Add(LDataRow); } #endregion }
public Excel_underlyingCalcInfo_para(XmlNode xmlNode) : base(xmlNode) { XmlNodeList excel_underlyingInfo_paraNodeList = xmlNode.SelectNodes("excel_underlyingInfo_para"); if (excel_underlyingInfo_paraNodeList != null) { this.excel_underlyingInfo_para_ = new List <Excel_underlyingInfo_para>(); foreach (XmlNode item in excel_underlyingInfo_paraNodeList) { if (item.Attributes["href"] != null || item.Attributes["id"] != null) { if (item.Attributes["id"] != null) { excel_underlyingInfo_paraIDRef_ = item.Attributes["id"].Value; excel_underlyingInfo_para_.Add(new Excel_underlyingInfo_para(item)); IDManager.SetID(excel_underlyingInfo_paraIDRef_, excel_underlyingInfo_para_[excel_underlyingInfo_para_.Count - 1]); } else if (item.Attributes["href"] != null) { excel_underlyingInfo_paraIDRef_ = item.Attributes["href"].Value; } else { excel_underlyingInfo_para_.Add(new Excel_underlyingInfo_para(item)); } } else { excel_underlyingInfo_para_.Add(new Excel_underlyingInfo_para(item)); } } } XmlNode excel_correlationInfo_paraNode = xmlNode.SelectSingleNode("excel_correlationInfo_para"); if (excel_correlationInfo_paraNode != null) { if (excel_correlationInfo_paraNode.Attributes["href"] != null || excel_correlationInfo_paraNode.Attributes["id"] != null) { if (excel_correlationInfo_paraNode.Attributes["id"] != null) { excel_correlationInfo_paraIDRef_ = excel_correlationInfo_paraNode.Attributes["id"].Value; Excel_correlationInfo_para ob = new Excel_correlationInfo_para(excel_correlationInfo_paraNode); IDManager.SetID(excel_correlationInfo_paraIDRef_, ob); } else if (excel_correlationInfo_paraNode.Attributes["href"] != null) { excel_correlationInfo_paraIDRef_ = excel_correlationInfo_paraNode.Attributes["href"].Value; } else { excel_correlationInfo_para_ = new Excel_correlationInfo_para(excel_correlationInfo_paraNode); } } else { excel_correlationInfo_para_ = new Excel_correlationInfo_para(excel_correlationInfo_paraNode); } } }
private void CrearDataSource() { try { //this.sqlConnection2.ConnectionString = this.ReportParameters["@Conexion"].Value.ToString(); ////Transfer the ReportParameter value to the parameter of the select command //this.sqlDataAdapter1.SelectCommand.Parameters["@Id_Emp"].Value = this.ReportParameters["@Id_Emp"].Value; //this.sqlDataAdapter1.SelectCommand.Parameters["@Id_Cd"].Value = this.ReportParameters["@Id_Cd"].Value; //this.sqlDataAdapter1.SelectCommand.Parameters["@Id_Ord"].Value = this.ReportParameters["@Id_Ord"].Value; // -------------------------------------------- // Generar source a partir del XML de factura // -------------------------------------------- if (this.source.Columns.Count == 0) { this.source.Columns.Add("Id_Prd", typeof(string)); this.source.Columns.Add("Prd_Descripcion", typeof(string)); this.source.Columns.Add("Prd_Unidad", typeof(string)); this.source.Columns.Add("Prd_Cantidad", typeof(string)); this.source.Columns.Add("Prd_PrecioUnitario", typeof(string)); this.source.Columns.Add("Prd_Importe", typeof(string)); } XmlDocument doc = new XmlDocument(); doc.LoadXml(this.ReportParameters["@FacturaXML"].Value.ToString()); //XmlNode nodoPage = doc.SelectSingleNode("//Page"); //string height = nodoPage.Attributes["height"].Value; //string width = nodoPage.Attributes["width"].Value; this.source.Rows.Clear(); XmlNodeList nodosProductos = doc.SelectNodes("//Concepto"); foreach (XmlNode producto in nodosProductos) { //XmlNode producto = xn.SelectSingleNode("Concepto"); if (producto.Attributes.Count > 0) { DataRow row = this.source.NewRow(); row["Id_Prd"] = producto.Attributes["noIdentificacion"].Value; row["Prd_Descripcion"] = producto.Attributes["descripcion"].Value; row["Prd_Unidad"] = "LT"; // producto.Attributes["cantidad"].Value; row["Prd_Cantidad"] = producto.Attributes["cantidad"].Value; row["Prd_PrecioUnitario"] = producto.Attributes["valorUnitario"].Value; row["Prd_Importe"] = producto.Attributes["importe"].Value; this.source.Rows.Add(row); } } // --------------------------------------------------------------------------------------------- // Si se asigno correctamente el origen de datos, se actualiza el estatus de la factura // --------------------------------------------------------------------------------------------- //actualiza estatus de factura a Impreso (I) int verificador = 0; Factura factura = new Factura(); factura.Id_Emp = Convert.ToInt32(this.ReportParameters["Id_Emp"].Value); factura.Id_Cd = Convert.ToInt32(this.ReportParameters["Id_Cd"].Value); factura.Id_Fac = Convert.ToInt32(this.ReportParameters["Id_Fac"].Value); factura.Fac_Estatus = "I"; new CN_CapFactura().ModificarFactura_Estatus(factura, this.ReportParameters["Conexion"].Value.ToString(), ref verificador); } catch (Exception ex) { throw ex; } }
static Match [] MakeNodesList (XmlNodeList nodes) { if (nodes.Count == 0) return null; Match [] list = new Match [nodes.Count]; for (int i = 0; i < list.Length; i ++) { Match m = new Match (GetNodeSignature (nodes [i]), false); m.Node = nodes [i]; list [i] = m; } return list; }
protected void Page_Load(object sender, EventArgs e) { if (Session["IDRED"] == null) { try { Response.Redirect("~/SesionCaducadaModal.aspx", true); } catch (System.Threading.ThreadAbortException) { return; } } string sPSN = Request.QueryString["sPSN"].ToString(); int idPSN = int.Parse(sPSN); string sRTPT = Request.QueryString["RTPT"].ToString(); //string sNomFich = Utilidades.decodpar(Request.QueryString["sPath"].ToString()); int iOrden = 1, iAssignmentUID = 1, iNumDias = 0, iNumDiasBase = 0;//, iUID=0 StringBuilder sb = new StringBuilder(); string sCodItem, sDenProy = "", sCodProy = "", sIniProy = "", sFinProy = "", sResponsable = "", sPdte = ""; //string sMaxUnits = "0.01000000000000000020816681711721685132943093776702880859375"; string sMaxUnits = "1"; decimal dParticipacion = 0, dParticipacionBase = 0, dEsfuerzo = 0, dEsfuerzoBase = 0, dEsfAcum = 0; string sCodUser = ""; bool bIncluirRecursos = false, bConLineBase = true; if (Request.QueryString["base"].ToString() == "N") { bConLineBase = false; } //try //{ if (sPSN != "") { #region Obtengo datos del proyectos a exportar idPSN = int.Parse(sPSN); SqlDataReader drP = PROYECTO.fgGetDatosProy4(idPSN); if (drP.Read()) { sCodProy = drP["t301_idproyecto"].ToString(); sDenProy = "Proyecto " + int.Parse(sCodProy).ToString("#,###") + ". " + drP["t301_denominacion"].ToString(); sIniProy = drP["t301_fiprev"].ToString(); sFinProy = drP["t301_ffprev"].ToString(); sResponsable = drP["Profesional"].ToString(); } drP.Close(); drP.Dispose(); #endregion } if (sCodProy != "") { #region Meto la cabecera del XML leyéndola de los datos de la plantilla guardados en la tabla T681_PLANTILLA_OPENPROJ //string sArchivoPlant = getPath("Plantilla_" + Session["IDFICEPI_ENTRADA"].ToString(), "xml"); SqlDataReader dr = OpenProj.GetPlantilla(null, 1); if (dr.Read()) { //byte[] fileData = (byte[])dr.GetValue(1); byte[] fileData; if (dr["t2_iddocumento"].ToString() != "") { fileData = IB.Conserva.ConservaHelper.ObtenerDocumento((long)dr.GetValue(0)).content; } else { //fileData = (byte[])dr.GetValue(1); throw new Exception("No se ha encontrado la plantilla de OpenProj en el repositorio de documentos"); } MemoryStream ms = new MemoryStream(); ms.Write(fileData, 0, fileData.Length); ms.Seek(0, SeekOrigin.Begin); //Hay que ponerse al principio porque sino el XML no se carga correctamente docxml.Load(ms); ms.Close(); } dr.Close(); dr.Dispose(); XmlNode nodoRaiz = docxml.DocumentElement; XmlNodeList LN = docxml.GetElementsByTagName("Name"); XmlNode nodoAux = LN.Item(0); nodoAux.InnerText = "Proyecto " + sCodProy; LN = docxml.GetElementsByTagName("Title"); nodoAux = LN.Item(0); nodoAux.InnerText = sDenProy; LN = docxml.GetElementsByTagName("Manager"); nodoAux = LN.Item(0); nodoAux.InnerText = sResponsable; LN = docxml.GetElementsByTagName("StartDate"); nodoAux = LN.Item(0); nodoAux.InnerText = OpenProj.flGetFechaOpenProj(sIniProy, "ID"); LN = docxml.GetElementsByTagName("FinishDate"); nodoAux = LN.Item(0); nodoAux.InnerText = OpenProj.flGetFechaOpenProj(sFinProy, "ID"); LN = docxml.GetElementsByTagName("CurrentDate"); nodoAux = LN.Item(0); nodoAux.InnerText = OpenProj.flGetFechaOpenProj(DateTime.Now.ToShortDateString(), "IJ"); //Pongo calendario 24x7 porque sino tiene en cuenta los fines de semana y recalcula la fecha de fin de las tareas LN = docxml.GetElementsByTagName("CalendarUID"); nodoAux = LN.Item(0); nodoAux.InnerText = OpenProj.fgGetCalendario(); //"2"; System.Xml.XmlElement Tasks = docxml.CreateElement("Tasks", en); System.Xml.XmlElement Assignments = docxml.CreateElement("Assignments", en); System.Xml.XmlElement Resources = docxml.CreateElement("Resources", en); #endregion #region cargo los recursos asociados a todas las tareas del proyecto //Cargo un recurso ficticio para tareas no asignadas a recursos //Resources.AppendChild(CrearResourceXml(docxml, "0", "0", "N", "No asignado", sMaxUnits, "3", "0", "3", "0", "0", "0")); Resources.AppendChild(OpenProj.CrearResourceXml(docxml, "1", "1", ".", "Ocupación diaria ", sMaxUnits, "3", "0", "3", "0", "0", "0")); //Resources.AppendChild(CrearResourceXml(docxml, "1", "1", "Perdiguero", "0.01000000000000000020816681711721685132943093776702880859375", "3", "0", "3", "0", "0", "10000")); if (bIncluirRecursos) { //Para cada recurso hay que meter un calendario XmlNodeList Calendarios = docxml.GetElementsByTagName("Calendars"); XmlNode nodoCalendario = Calendarios.Item(0);//Calendarios.Count - 1 SqlDataReader dr2 = OpenProj.GetProfesionales(null, idPSN, true); while (dr2.Read()) { sCodUser = dr2["t314_idusuario"].ToString(); System.Xml.XmlNode Calendario = nodoCalendario.AppendChild(OpenProj.CrearCalendarioUsuarioXml(docxml, sCodUser, dr2["Profesional"].ToString(), "2")); Resources.AppendChild(OpenProj.CrearResourceXml(docxml, sCodUser, sCodUser, sCodUser, dr2["Profesional"].ToString(), sMaxUnits, "3", "0", "3", "0", "0", "0")); } dr2.Close(); dr2.Dispose(); } #endregion #region Meto los items del proyecto bool bHayRecursos = false; SqlDataReader dr1; if (sRTPT == "0") { dr1 = OpenProj.GetEstructura(null, idPSN); } else { dr1 = OpenProj.GetEstructura(null, idPSN, int.Parse(Session["UsuarioActual"].ToString())); } while (dr1.Read()) //foreach (int iKey in htItems.Keys) { //ItemsProyecto oItem = new ItemsProyecto(); //oItem = (ItemsProyecto)htItems[iKey]; ItemsProyecto oItem = new ItemsProyecto((int)dr1["codPT"], (int)dr1["codFase"], (int)dr1["codActiv"], (int)dr1["codTarea"], dr1["nombre"].ToString(), dr1["descripcion"].ToString(), dr1["tipo"].ToString(), iOrden++, /*(int)dr1["orden"],*/ dr1["FIPL"].ToString(), dr1["FFPL"].ToString(), decimal.Parse(dr1["ETPL"].ToString()), dr1["PRIMER_CONSUMO"].ToString(), dr1["ULTIMO_CONSUMO"].ToString(), dr1["FFPR"].ToString(), decimal.Parse(dr1["ETPR"].ToString()), decimal.Parse(dr1["Consumido"].ToString()), dr1["SITUACION"].ToString(), ((int)dr1["FACTURABLE"] == 0) ? false : true, (int)dr1["MARGEN"]); sCodItem = ""; string sIdent = OpenProj.flGetIdentacion(oItem.margen); switch (oItem.tipo) { case "P": sCodItem = oItem.codPT.ToString(); break; case "F": sCodItem = oItem.codFase.ToString(); break; case "A": sCodItem = oItem.codActiv.ToString(); break; case "T": case "HF": sCodItem = oItem.codTarea.ToString(); break; } //if (sCodItem == "143637") // sCodItem = sCodItem; if (sCodItem != "" && oItem.FIPL != "" && oItem.FFPL != "") { //if (oItem.codTarea == 148600) oItem.Consumido = 6; //if (oItem.Consumido != 0) sPdte = OpenProj.flPdteOpenProj(oItem.ETPR, oItem.Consumido); //else //sPdte = ""; bHayRecursos = false; sCodUser = "******"; dEsfAcum = 0; iNumDiasBase = OpenProj.flDuracionDias(oItem.FIPL, oItem.FFPL); iNumDias = OpenProj.flDuracionDias(oItem.PRIMER_CONSUMO, oItem.FFPR); dEsfuerzo = oItem.EsfuerzoHoras; dEsfuerzoBase = oItem.ETPL; //Hay que dividir por el nº de dias de duración de la tarea if (iNumDiasBase != 0) { dParticipacionBase = dEsfuerzoBase / (iNumDiasBase * 8); } else { dParticipacionBase = 0; } //if (dParticipacionBase > 1) dParticipacionBase = 1; if (iNumDias != 0) { dParticipacion = dEsfuerzo / (iNumDias * 8); } else { dParticipacion = 0; } //if (dParticipacion > 1) dParticipacion = 1; Tasks.AppendChild( OpenProj.CrearTareaXml(docxml, sCodItem, oItem.orden.ToString(), oItem.nombre, oItem.descripcion, oItem.tipo, sIdent, "0", OpenProj.flGetFechaOpenProj(oItem.PRIMER_CONSUMO, "IJ"), OpenProj.flGetFechaOpenProj(oItem.FFPR, "FJ"), OpenProj.flDuracionOpenProj(0, oItem.PRIMER_CONSUMO, oItem.FFPR), "7", "0", "2", sPdte, oItem.Consumido, oItem.FIPL, oItem.FFPL, oItem.ETPL, oItem.ETPR, dParticipacion, bConLineBase) ); #region Meto los recursos asociados a cada tarea y las asignaciones de la situación actual //Resources.AppendChild(CrearResourceXml(docxml, "1", "1", "Perdiguero", "0.01000000000000000020816681711721685132943093776702880859375", "3", "0", "3", "0", "0", "10000")); if (bIncluirRecursos) { #region Incluyendo recursos if (oItem.tipo == "T") { //De momento como no tengo claro lo que hay que hacer con los recursos, solo los calculo para las tareas //Luego, si hace falta, ya pondré los de PT, F y A. Según la reunión del 8/9/2011 con Iñigo Garro //basta con asociar los recursos a las tareas //Leer de BBDD los recursos asignados a la tarea SqlDataReader dr3 = OpenProj.GetProfesionalesTarea(null, int.Parse(sCodItem), true); while (dr3.Read()) { bHayRecursos = true; sCodUser = dr3["t314_idusuario"].ToString(); //Segundo hay que calcular el porcentaje de participación del usuario en la tarea // Para ello yo haria t336_etp / oItem.ETPR (si fuera división por cero, devolver cero) if (dr3["t336_etp"].ToString() == "") { dEsfuerzo = 0; } else { dEsfuerzo = decimal.Parse(dr3["t336_etp"].ToString()); } dEsfAcum += dEsfuerzo; //if (oItem.ETPR == 0 || dr3["t336_etp"].ToString()=="") // dParticipacion = 0; //else // dParticipacion = decimal.Parse(dr3["t336_etp"].ToString()) / oItem.ETPR; //Hay que dividir el esfuerzo en horas por el nº de dias de duración de la tarea if (iNumDiasBase != 0) { dParticipacionBase = dEsfuerzo / (iNumDiasBase * 8); } else { dParticipacionBase = 0; } if (iNumDias != 0) { dParticipacion = dEsfuerzo / (iNumDias * 8); } else { dParticipacion = 0; } Assignments.AppendChild( OpenProj.CrearAssignmentXml(docxml, oItem, iAssignmentUID.ToString(), sCodUser, dEsfuerzo, dParticipacion, dParticipacionBase, sPdte, bConLineBase, iNumDias)); iAssignmentUID++; } dr3.Close(); dr3.Dispose(); if (bHayRecursos) { //Si la suma de los esfuerzos asignados a la tarea no llegan al esfuerzo total de la tarea //metemos las horas que faltan al recurso imaginario (Sino, no respeta el esfuerzo de la tarea) if (dEsfAcum < oItem.EsfuerzoHoras) { sCodUser = "******"; dEsfuerzo = oItem.EsfuerzoHoras - dEsfAcum; if (iNumDias != 0) { dParticipacion = dEsfuerzo / (iNumDias * 8); } else { dParticipacion = 0; } Assignments.AppendChild( OpenProj.CrearAssignmentXml(docxml, oItem, iAssignmentUID.ToString(), sCodUser, dEsfuerzo, dParticipacion, dParticipacionBase, sPdte, bConLineBase, iNumDias)); iAssignmentUID++; } } else { //meto los elementos Assignement que contiene para cada item del proyecto un elemento por cada día del intervalo Assignments.AppendChild( OpenProj.CrearAssignmentXml(docxml, oItem, iAssignmentUID.ToString(), sCodUser, dEsfuerzo, dParticipacion, dParticipacionBase, sPdte, bConLineBase, iNumDias)); iAssignmentUID++; } } else { //El item no es una tarea -> asignamos recurso ficticio ¿seguro que es necesario? Assignments.AppendChild( OpenProj.CrearAssignmentXml(docxml, oItem, iAssignmentUID.ToString(), "1", dEsfuerzo, dParticipacion, dParticipacionBase, sPdte, bConLineBase, iNumDias)); iAssignmentUID++; } } #endregion else { //En el criterio de exportación hemos marcado "No coger recursos" -> asignamos recurso ficticio switch (oItem.tipo) { //case "PT": //case "P": //case "F": //case "A": // Assignments.AppendChild( // OpenProj.CrearAssignmentPadreXml(docxml, oItem, iAssignmentUID.ToString(), "-65535")); // iAssignmentUID++; // break; case "T": Assignments.AppendChild( OpenProj.CrearAssignmentXml(docxml, oItem, iAssignmentUID.ToString(), "1", dEsfuerzo, dParticipacion, dParticipacionBase, sPdte, bConLineBase, iNumDias)); iAssignmentUID++; break; case "HF": Assignments.AppendChild( OpenProj.CrearAssignmentXml(docxml, oItem, iAssignmentUID.ToString(), "1", 0, 1, 1, "", false, iNumDias)); iAssignmentUID++; break; } } #endregion } } dr1.Close(); dr1.Dispose(); #endregion nodoRaiz.AppendChild(Tasks); nodoRaiz.AppendChild(Resources); nodoRaiz.AppendChild(Assignments); string sNumProy = PROYECTO.flGetNumProy(null, idPSN); sNumProy = sNumProy.Replace(@"@", @"_"); string sArchivoSalida = Session["IDFICEPI_ENTRADA"].ToString() + "_Proyecto_" + sNumProy + "_" + DateTime.Now.Ticks.ToString() + ".xml"; Response.ClearContent(); Response.ClearHeaders(); Response.Buffer = true; Response.AddHeader("Content-Disposition", "attachment; filename=\"" + sArchivoSalida + "\""); Response.ContentType = "text/xml"; //RFC 3023 //Lo codifico en UTF8 para que respete los caracteres especialed (Ñ, tíldes, etc...) Response.BinaryWrite(Encoding.UTF8.GetBytes(docxml.OuterXml)); //Response.Flush(); //Response.Close(); Response.End(); } //} //catch (Exception ex) //{ // //return "Error@#@" + Errores.mostrarError("Error al generar el fichero XML con la estructura del proyecto.", ex); // return "Error@#@Error al generar el fichero XML con la estructura del proyecto. " + ex.Message; //} }