-
Posts
595 -
Joined
-
Last visited
-
Days Won
4
Everything posted by bc-vnt
-
Scanning result Download it Form1 Public Class Form1 Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim word As String = "abc" Dim mainList As New List(Of String) Dim counter As Integer = 0 'counter Dim newString As String = " " 'We're going to generate every possible combination ' using binary techniques. ' Every combination for word.length long strings While (newString.Length <= word.Length) newString = Convert.ToString(counter, 2) 'Convert the number to Base 2 mainList.Add(newString) counter += 1 End While 'This method unfortunately leaves us with one extra item on our list, which we can delete mainList.RemoveAt(mainList.Count - 1) 'Also, the first item is going to be invalid ( "0000" will mean 4 blanks later on, which isn't valid) mainList.RemoveAt(0) 'Now we're going to make all the strings the same length.. still binary technique ' for each element, add a 0 to the front of the string until eElement is the same length ' as word (so for word "abcd" we want "0000", "0001", "0010" instead of "0", "1", "10", etc For i = 0 To mainList.Count - 1 While Not (mainList(i).Length = word.Length) mainList(i) = "0" & mainList(i) End While Next 'Now we organize our binary data into a way useful for us ' first, when we have 0 blanks, then 1 blank, then 2 blanks, all the way up until word.length-1 Dim sortedList As New List(Of String) ' [i] is the amount of blanks. we start by looking for 0, then 1, all the way to word.length For i = 0 To mainList.Count - 1 ' for each element in the list, "0000","0001","0010",..."1111" For Each eElement As String In mainList Dim numberOfBlanks As Integer = 0 ' find how many blanks (or "0"s) there are in this element For Each eChar As Char In eElement ' if it's blank ("0") , add one to this counter variable If (eChar = "0") Then numberOfBlanks += 1 End If Next ' first we were look for 0 blanks (then 1, then 2, etc) ' so on the first pass we only add elements that have a matching ' numberOfBlanks to what we're looking for If (numberOfBlanks = i) Then sortedList.Add(eElement) End If Next Next Dim parallelList As New List(Of String) 'hopefully we don't have to delete all the new variables.. End Sub End Class Normal level Option Strict On Public Class NormalEvilForm Private Sub DisableGame() GuessLetterButton.Enabled = False GuessLetterTextBox.Enabled = False LetterChoicePanel.Enabled = False SolveForMeButton.Enabled = False End Sub Private Sub Win() DisableGame() TitleLabel.Text = "You Win!" GameOverTimer.Start() End Sub Private Sub Lose() DisableGame() TitleLabel.Text = "You Lose! The Word Was:" GuessesLeftLabel.Text = "0" SolveForMe() GenerateWordCountLabel() GameOverTimer.Start() End Sub Private Sub SetupLabels() GuessesLeftLabel.Text = (GuessesLeft).ToString GenerateWordCountLabel() End Sub Private Sub SetRemainingGuesses() GuessesLeftLabel.Text = GuessesLeft.ToString End Sub Private Sub GenerateWordCountLabel() WordCountLabel.Text = String.Empty For Counter As Integer = 0 To CharactersOfWord.Count - 1 Dim Letter As String = CharactersOfWord(Counter) If Letter = " " Then WordCountLabel.Text &= " " Else If CorrectGuesses(Counter) = True Then WordCountLabel.Text &= Letter & " " Else WordCountLabel.Text &= "_ " End If End If Next End Sub Private Sub AddLetterButtonEvents() For Each Item As Button In LetterChoicePanel.Controls If Item.Tag.ToString <> String.Empty Then 'AddHandler Item.MouseHover, AddressOf LetterButton_Event AddHandler Item.GotFocus, AddressOf LetterButton_Event End If Next End Sub Private Sub LetterButton_Event(ByVal sender As System.Object, ByVal e As System.EventArgs) Dim LetterButton As Button = TryCast(sender, Button) GuessLetterTextBox.Text = LetterButton.Tag.ToString GuessLetterButton.Focus() End Sub Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ChooseWord() AddLetterButtonEvents() GenerateCharactersOfWord() SetupLabels() End Sub Private Sub LetterGuessed(ByVal Letter As String) GuessedLetters.Add(Letter) Dim CorrectGuess As Boolean = False For Counter As Integer = 0 To CharactersOfWord.Count - 1 If CharactersOfWord(Counter).ToLower = Letter.ToLower Then CorrectGuesses(Counter) = True CorrectGuess = True End If Next If CorrectGuess = False Then GuessesLeft -= 1 GuessesLeftLabel.Text = (GuessesLeft).ToString End If End Sub Private Sub GuessLetterButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GuessLetterButton.Click If GuessLetterTextBox.Text <> String.Empty Then For Each Item As Button In LetterChoicePanel.Controls If Item.Tag.ToString = GuessLetterTextBox.Text Then Item.Enabled = False End If Next If GameType = GameMode.Evil Then EvilHangmanFunction(GuessLetterTextBox.Text) End If LetterGuessed(GuessLetterTextBox.Text) GenerateWordCountLabel() If GameType = GameMode.Evil Then CheckCorrectGuesses() End If If CheckWin() = True Then Win() ElseIf CheckLose() = True Then Lose() End If GuessLetterTextBox.Clear() End If GuessLetterTextBox.Focus() End Sub Private Sub GuessTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles GuessLetterTextBox.KeyPress If Not Char.IsLetter(e.KeyChar) Then e.Handled = True Else For Each Letter As String In GuessedLetters If e.KeyChar = Letter.ToLower Then e.Handled = True Exit Sub End If Next GuessLetterTextBox.Text = String.Empty End If End Sub Private Sub GameOverTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles GameOverTimer.Tick GameOverTimer.Stop() Dim Result As DialogResult = _ MessageBox.Show("Would you like to play another game?", "Project Hangman - Game Over", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) If Result = DialogResult.Yes Then Reset() StartupForm.Show() Me.Close() Else Application.Exit() End If End Sub Private Sub SolveForMeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SolveForMeButton.Click Lose() End Sub End Class Project module Option Strict On Imports System.IO Module ProjectHangmanModule Enum GameMode Normal Evil Ultimate End Enum Public GameType As GameMode = GameMode.Normal Public Word As String Public WordLength As Integer '2-24 Public WordList As New List(Of String) Public CharactersOfWord As New List(Of String) Public CorrectGuesses As New List(Of Boolean) Public GuessedLetters As New List(Of String) Public GuessesLeft As Integer Public Win As Boolean = False Public Lose As Boolean = False Private RandomClass As New Random() Public Sub Reset() Word = "" WordLength = 0 WordList.Clear() CharactersOfWord.Clear() CorrectGuesses.Clear() GuessedLetters.Clear() GuessesLeft = 0 Win = False Lose = False End Sub Public Sub ChooseWord() Try Dim TextFile As New StreamReader("WordList.txt") While TextFile.EndOfStream = False WordList.Add(TextFile.ReadLine()) End While For Counter As Integer = WordList.Count - 1 To 0 Step -1 If WordList(Counter).Length <> WordLength Then WordList.RemoveAt(Counter) End If Next Word = WordList(RandomClass.Next(0, WordList.Count)) Catch ex As Exception MessageBox.Show("Error:" & ControlChars.NewLine & ex.Message, "Hangman - Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) End Try End Sub Public Sub EvilHangmanFunction(ByVal Letter As String) 'Convert the letter to lower case Letter = Letter.ToLower() 'A list of all lists of words containing or not containing the given letter Dim TotalList As New List(Of List(Of String)) 'Create a sub list to the total list for each letter in the word 'and one for the word not containing the letter For Counter As Integer = 0 To WordLength - 1 Dim SubList As New List(Of String) TotalList.Add(SubList) Next 'For Each word in the current word list For Each Word As String In WordList Dim ContinueFor As Boolean = False 'For Each letter in the word For Counter As Integer = 0 To Word.Length - 1 'If the letter is the letter given to the function If Word.Substring(Counter, 1) = Letter Then 'add the word to the list, based on the counter TotalList(Counter).Add(Word) End If Next Next 'Now find the sub list that contains the most elements Dim highestCountIndex As Integer = 0 Dim highestCount As Integer = 0 For Counter = 0 To TotalList.Count - 1 If (highestCount < TotalList(Counter).Count) Then highestCount = TotalList(Counter).Count highestCountIndex = Counter End If Next 'A temporary list to store words in Dim TempList As New List(Of String) 'For each word not containing the letter For Each Word As String In WordList If Not Word.Contains(Letter) Then 'Add the word to the temp list TempList.Add(Word) End If Next 'Clea the word list WordList.Clear() 'If the temp list has elements If TempList.Count <> 0 Then For Each Word As String In TempList 'Populate WordList by the words in the TempList WordList.Add(Word) Next Else 'If TempList.Count = 0 For Each Word As String In TotalList(highestCountIndex) 'Populate WordList by the words in the list with the most elements WordList.Add(Word) Next End If 'Next set Word to a new random word, in the new list Word = WordList(RandomClass.Next(0, WordList.Count)) GenerateCharactersOfWord() End Sub Public Sub GenerateCharactersOfWord() CorrectGuesses.Clear() CharactersOfWord.Clear() For Counter As Integer = 0 To Word.Length - 1 Dim Letter As String Letter = Word.Substring(Counter, 1) CharactersOfWord.Add(Letter) Dim LetterGuessed As Boolean = False For Each GLetter In GuessedLetters If GLetter.ToLower = Letter.ToLower Then LetterGuessed = True End If Next Dim ALetter As Boolean = False If Letter = " " Or LetterGuessed = True Then ALetter = True End If CorrectGuesses.Add(ALetter) Next End Sub Public Sub CheckCorrectGuesses() For Each Item As String In GuessedLetters For Counter As Integer = 0 To WordLength - 1 If Word.Substring(Counter, 1) = Item.ToLower Then CorrectGuesses(Counter) = True End If Next Next End Sub Public Sub SolveForMe() For Counter As Integer = 0 To CorrectGuesses.Count - 1 CorrectGuesses(Counter) = True Next End Sub Public Function CheckWin() As Boolean For Each Letter As Boolean In CorrectGuesses If Letter = False Then Return False End If Next Return True End Function Public Function CheckLose() As Boolean If GuessesLeft = 0 Then Return True Else Return False End If End Function End Module Start UP Public Class StartupForm Private Sub ShowOptions() Me.Size = New Size(806, 342) OptionsPanel.Enabled = True WordLengthNumericUpDown.Focus() End Sub Private Sub SetSelectedButton(ByVal Button As GameMode) Select Case Button Case GameMode.Normal NormalButton.ForeColor = Color.Blue EvilButton.ForeColor = Color.Black UltimateButton.ForeColor = Color.Black Case GameMode.Evil NormalButton.ForeColor = Color.Black EvilButton.ForeColor = Color.Blue UltimateButton.ForeColor = Color.Black Case GameMode.Ultimate NormalButton.ForeColor = Color.Black EvilButton.ForeColor = Color.Black UltimateButton.ForeColor = Color.Blue End Select End Sub Private Sub NormalButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NormalButton.Click GameType = GameMode.Normal SetSelectedButton(GameType) ShowOptions() Me.AcceptButton = StartButton End Sub Private Sub EvilButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EvilButton.Click GameType = GameMode.Evil SetSelectedButton(GameType) ShowOptions() Me.AcceptButton = StartButton End Sub Private Sub UltimateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UltimateButton.Click GameType = GameMode.Ultimate SetSelectedButton(GameType) UltimateForm.Show() Me.Close() End Sub Private Sub StartButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartButton.Click WordLength = WordLengthNumericUpDown.Value GuessesLeft = NumberOfGuessesNumericUpDown.Value NormalEvilForm.Show() Me.Size = New Size(806, 212) Me.Close() End Sub Private Sub NumberOfGuessesNumericUpDown_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles _ NumberOfGuessesNumericUpDown.GotFocus, _ NumberOfGuessesNumericUpDown.Click NumberOfGuessesNumericUpDown.Select(0, 2) End Sub Private Sub WordLengthNumericUpDown_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles _ WordLengthNumericUpDown.GotFocus, _ WordLengthNumericUpDown.Click WordLengthNumericUpDown.Select(0, 2) End Sub End Class Enjoi ... !!!
-
- 1
-
-
I am reading Jesse Storimer’s fantastic little book “Working with UNIX processes” right now, and inspiration struck after the second chapter “Processes Have Parents”. When a Unix process is born, it is a literal copy of it’s parent process. For example, if I am typing ls into a bash prompt, the bash process spawns a copy of itself using the fork system call. The parent process (bash) has an id which is associated with the child process (ls). Using the Unix ps command, you can see the parent process id of every process on the system. The only process that has no parent is sched, it has process id zero. The idea I had was to make a visualization of this branching tree of Unix processes. I am currently running Debian GNU/Linux, a Unix variant. I came up with this one-liner that shows the (parent id -> child id) relation: ps axo ppid,pid | sed "s/\b / -> /g" | grep -v "PID" The first part calls ps and gets all process ids, and their parents. Some sample output is this: ~ > ps axo ppid,pid PPID PID 0 1 0 2 2 3 2 6 2 7 2 8 2 10 2 12 2 13 This output is piped into sed (stream editor), and the empty space between the numbers is replaced with an arrow “->”: ~ > ps axo ppid,pid | sed "s/\b / -> /g" PPID -> PID 0 -> 1 0 -> 2 2 -> 3 2 -> 6 2 -> 7 2 -> 8 2 -> 10 2 -> 12 2 -> 13 ... PPID is Parent Process Id, and PID is just Process Id. Finally, I use grep -v “PID” to let all the lines through that don’t contain “PID”. This selects those lines that are actual process relations. In this case, it just chops off the first line. Next, I wanted to convert this into a file that I can feed into GraphViz, an open source graph visualization tool. The format is pretty simple, an example is in order: digraph Foo { 1 -> 2 1 -> 3 } The above file defines a graph called “Foo” that has three nodes and two edges, it looks like this: Now, all we have to do to the PPID->PID output above is to wrap it in braces and prepend two words to the beginning. We can use echo “digraph proc { SOME COMMAND }” to wrap the output of our command, then dump the results in a file. echo "digraph proc { `ps axo ppid,pid | sed "s/\b / -> /g" | grep -v "PID"` } " >> proc.dot Finally, GraphViz has several commands for rendering graphs in various ways. The first thing I tried was a symmetric layout, but that produced a hierarchical, very wide image. So I tryed circo which produces a radial layout: ~ > echo "digraph proc { `ps axo ppid,pid | sed "s/\b / -> /g" | grep -v "PID"` } " >> proc.dot ~ > circo proc.dot -Tpng >> radial_proc.png Here’s the radial layout: You can see the original ancestor of all processes, sched with PID 0 right in the center, then PID 1 which is called init has a bunch of children. I am writing this post in vim in a bash shell in a gnome terminal emulator, the vim PID is 14819, but it is hard to see in this image, there is too much overlap. Fortunately, we can modify the proc.dot file and include overlap=false right above the PPID->PID pairs. Also, I found from the man pages for the graphviz tools that the splines=true option will draw the edges as splines (curves) instead of straight lines. Also, instead of using circo, there is another tool called neato that will render a more symmetrical graph than circo. This rendering took much longer than circo rendering, but is much nicer (click to enlarge): I remember learning in my C programming class that Unix processes all had to be made with fork. It reminded me of asexual reproduction where two identical copies are made. I look forward to learning more about the Unix process model, and recommend Jesse’s book. Download free book " Working with UNIX processes " http://tobilehman.com/blog/2012/10/14/unix-processes-and-their-parents/
-
Vazand ca poarta este incuiata , mi-am pus fesul pe cap pentru a sparge zidul sa ajug latoaleta , pentru ca aveam nevoie urgent . Sper ca am gandit bine .
-
Brute foloseste orice HASH sau Encriptie standard. Algoritmi de baza sunt : HASH MD5 SHA Scanning result Download it Print Sursa de inspiratie
-
Cred ca a venit timpul sa ma prezint si eu , Bc-Vnt , initialele numelui meu Valentin , prenumele nu il pun. Forumul foarte bun pentru cine vrea sa invete , acum ceva timp nu stiam mai nimic despre computer-e , dar intrand in aceasta comunitate am invatat o groaza de lucruri , bune / rele ,mai mult bune asta nu conteaza . Varsta mea este aproapte de 21 de ani , in timp de cateva luni am invatat Visual basic .NET , PHP , nu foarte mult ,inca invat , multumesc celor care au postat tutoriale pentru incepatpri , iar eu la randul meu voi face tot posibilul sa ajut incepatori , chiar si pe cei mai avansati , pentru ca " In viata omul cat traieste invata " sper ca cei mai vechi si cei mai trecuti prin viata stiu ce inseamna aceasta zicala . Despre mine , ce sa va spun , imi plac sportul ( nu prea am un corp atletic ) , dar mi-a placut si imi place inca , muzica manele , hip-hop , rap ,straine si romanesti . Computerul image In rest , sper sa avem un raport de colegialitate cat mai bun si spor la invatat tuturor .
-
Man ,eu faceam comenzi prin telefon , acum am dat un search pe google si am vazut ca au site , deci eu recomand cu mare incredere ,cei care sunt din Constanta pot confirma .
- 31 replies
-
- livrare pizza craiova
- pizza craiova
- (and 3 more)
-
RSA Introduction The RSA (Rivest, Shamir, Adleman) encryption algorithm uses two Keys: Private and Public. Scenario A Suppose Alice wants to send a message to Bob (for his eyes only!). She can encrypt the message using the RSA algorithm with Bob's Public Key, which is not a secret (that's why they call it Public…). Once the message is encrypted, nobody can decrypt it, except the one holding the matching Private Key (that is Bob). Scenario B The reverse is also true: if Alice would encrypt the message using her own Private Key, Bob (and Eve, and everyone who can access this "encrypted" message) can decrypt it using Alice's Public Key. So, if everybody can decrypt it, what's the point in encrypting the message with a Private Key in the first place? Well, there is a point if Bob wants to make sure that the message has been written by Alice and not by someone else (Eve?). .NET RSACryptoServiceProvider The .NET Framework implements the RSA algorithm in the RSACryptoServiceProvider class. The instance of this class lets you create Key pairs, encrypt using a public key, decrypt using a private key (as in the first scenario), sign (sort of the second scenario, but not exactly), and verify the signature. The Sign method accepts a message (as byte array) and creates a signature for this particular data. In the second scenario, Alice can write a message to Bob, and use this method to get a signature with her own private key. Then, she can send the message to Bob as is (unencrypted) with the signature. To verify the writer ID (Alice), Bob will use the Verify method with Alice's public key as: Verify(aliceMessage, aliceSignature), and he will get "true" if this is the original message written and signed by Alice, or "false" if even one bit has been changed since. This is one useful implementation of private key encryption, but sometimes it's just too complicated. You might want to send just a little message so the receiver can decrypt it and be sure it's from you, without the need to sign and send him both components. RSA Private Key Encryption Unfortunately, the RSACryptoServiceProvider class does not provide you this option, so I wrote my own implementation of the RSA algorithm using the basics of the RSACryptoServiceProvider in conjunction with Chew Keong TAN's class: BigInteger C# BigInteger Class - CodeProject At a low level, the RSA algorithm is about implementing mathematical equations on huge (huge) integers, so the BigInteger class is really essential. I couldn't have done it myself. Using the RSAEncryption Class The class has six main methods: void LoadPublicFromXml(string publicPath) void LoadPrivateFromXml(string privatePath) byte[] PrivateEncryption(byte[] data) byte[] PublicEncryption(byte[] data) byte[] PrivateDecryption(byte[] encryptedData) byte[] PublicDecryption(byte[] encryptedData) I believe the method names are self explanatory. First, you have to create a private / public key pair, using the .NET RSACryptoServiceProvider class. To do that, you just create an instance of this class and then call the appropriate methods, like this: void LoadPublicFromXml(string publicPath) RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); File.WriteAllText(@"C:\privateKey.xml", rsa.ToXmlString(true)); // Private Key File.WriteAllText(@"C:\publicKey.xml", rsa.ToXmlString(false)); // Public Key // Then, you can load those files to RSAEncryption instance: RSAEncryption myRsa = new RSAEncryption(); myRsa.LoadPrivateFromXml(@"C:\privateKey.xml"); myRsa.LoadPublicFromXml(@"C:\publicKey.xml"); // Once the keys are loaded (if you load a private key, there is no need to // load the public one) you can start Encrypt / Decrypt data // using Private / Public keys. byte[] message = Encoding.UTF8.GetBytes("My secret message"); byte[] encryptMsg = myRsa.PrivateEncryption(message); byte[] decryptMsg = myRsa.PublicDecryption(encryptMsg); string originalMsg = Encoding.UTF8.GetString(decryptMsg); // returns "My secret message" WinForms Tester Application To help you get started with the RSAEncryption and the RSACryptoServiceProvider classes, I wrote a WinForms tester application that uses those classes. All you need to do is just play with it a little and read the code-behind. Update: New Version The new implementation of the RSA Private Encryption has a few advantages: Bug fix: Added random padding to support 0 bytes prefix data. Uses the new .NET 4 "BigInteger" struct for math support. Extension methods implementation: the only class instance needed is RSACryptoServiceProvider. Better Exceptions and error handling. UnitTest project added. Generally, more elegant code (I hope..!). Using the New Version string secret = "My secret message"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512); // Key bits length /* * Skip the loading part for the RSACryptoServiceProvider will generate * random Private / Public keys pair, that you can save later with * rsa.ToXmlString(true); * string key = "private or public key as xml string"; rsa.FromXmlString(key); */ // Convert the string to byte array byte[] secretData = Encoding.UTF8.GetBytes(secret); // Encrypt it using the private key: byte[] encrypted = rsa.PrivareEncryption(secretData); // Decrypt it using the public key byte[] decrypted = rsa.PublicDecryption(encrypted); string decString = Encoding.UTF8.GetString(decrypted); // And back to string Assert.AreEqual("My secret message", decString); Download source http://www.codeproject.com/Articles/38739/RSA-Private-Key-Encryption
-
Pentru Constanta : Fast Food Pizza Kebab Shaorma Meniuri Paste | Constanta - este cea mai buna pizzerie din oras .
- 31 replies
-
- livrare pizza craiova
- pizza craiova
- (and 3 more)
-
Scanning result Download it Just press " Go "
-
Introduction MSXML, a window component shipped with Windows / Office and other microsoft products, exists in all windows platforms. But there are different versions of MSXML, from 2.6 to 6.0, which causes a lot of problems. This is a wrapping class library for MSXML 3.0/4.0/5.0/6.0 consisting of resolving the above problem -- you don't need worry about the available MSXML version on different machines any more. and also it provides easy-to-use interface -- each node in the xml is considered as an object and you can use some code like below to locate a node. xml.GetRoot()->GetChild(_T("a"))->GetChild(_T("b"))->GetChild(_T("c")) Sample Code Please find the sample code in the demo project. Using the Code Copy all the files in the /CXml/*.* directory and add them into your project. #include "Xml.h" using namespace JWXml; Here, I have added a namespace for the classes, you can change it as you like. MSXML Version The class will try to choose the version of MSXML in the following order: hr = (hr == S_OK) ? hr : m_pDoc.CreateInstance( __uuidof(MSXML2::DOMDocument60) ); hr = (hr == S_OK) ? hr : m_pDoc.CreateInstance( __uuidof(MSXML2::DOMDocument30) ); hr = (hr == S_OK) ? hr : m_pDoc.CreateInstance( __uuidof(MSXML2::DOMDocument50) ); hr = (hr == S_OK) ? hr : m_pDoc.CreateInstance( __uuidof(MSXML2::DOMDocument40) ); hr = (hr == S_OK) ? hr : m_pDoc.CreateInstance( __uuidof(MSXML2::DOMDocument26) ); hr = (hr == S_OK) ? hr : m_pDoc.CreateInstance( __uuidof(MSXML2::DOMDocument) ); Classes Overview CXml class CXml { friend class CXsl; public: CXml(void); ~CXml(void); protected: MSXML2::IXMLDOMDocument2Ptr m_pDoc; CString m_strFilePath; MSXML_VERSION m_emVersion; std::map< CString, CString> m_mpNamespace; BOOL CreateInstance(void); public: // Open XML file BOOL Open(LPCTSTR lpszXmlFilePath); // Create a new XML file BOOL Create( LPCTSTR lpszRootName = _T("xmlRoot") , LPCTSTR lpszPrefix = _T("") , LPCTSTR lpszNamespaceURI = _T("") ); // Load XML string BOOL LoadXml(LPCTSTR lpszXmlContent); // save XML file BOOL Save(LPCTSTR lpszFilePath); // save XML file with formatted output BOOL SaveWithFormatted(LPCTSTR lpszFilePath = NULL, LPCTSTR lpszEncoding = _T("UTF-8")); // close XML file void Close(void); CString GetXmlFile(void) const; // Encode the binary data into string CString Base64Encode( LPBYTE pBuf, ULONG ulSize); // Decode the string into binary data BOOL Base64Decode( CString strIn, LPBYTE pBuf, LONG & lSize); // namespace void AddSelectionNamespace( LPCTSTR lpszPrefix, LPCTSTR lpszURI); // get the root element of CXmlNodePtr GetRoot(void); // get single node by XPath CXmlNodePtr SelectSingleNode(LPCTSTR lpszPath); // get nodes by XPath CXmlNodesPtr SelectNodes(LPCTSTR lpszPath); // create node CXmlNodePtr CreateNode(LPCTSTR lpszName , LPCTSTR lpszPrefix = _T("") , LPCTSTR lpszNamespaceURI = _T("") ); // get the current version of MSXML MSXML_VERSION GetVersion(void) const; }; CXmlNode class CXmlNode { friend class CXml; friend class CXmlNode; friend class CXmlNodes; protected: MSXML2::IXMLDOMNodePtr m_pNode; CXmlNode( MSXML2::IXMLDOMNodePtr pNode); BOOL _GetValue(CString & strValue) const; BOOL _SetValue(CString & strValue) const; BOOL _GetAttribute( CString & strName, CString & strValue) const; BOOL _SetAttribute( CString & strName IN , CString & strValue IN , CString & strPrefix IN , CString & strNamespaceURI IN ) const; public: CXmlNode(void); CXmlNode(const CXmlNode & refNode IN); CXmlNode(const CXmlNodePtr pNode IN); ~CXmlNode(void); CXmlNodePtr operator = (CXmlNodePtr pNode); CXmlNode & operator = (const CXmlNode & refNode); BOOL IsNull(void) const; // Whether the current element exist CString GetName(void) const;// Get the name of the current node CXmlNode & Detach(void); // Detach the current node void Release(void); // Release this node CXmlNodePtr GetChild( CString strName, BOOL bBuildIfNotExist = TRUE); CXmlNodePtr NewChild( CString strName ); CXmlNodePtr GetParent(void); CXmlNodesPtr GetChildren(); void AttachChild( CXmlNodePtr & pChildNode); void AttachChild( CXmlNode & refChildNode); BOOL HasChildren(void); BOOL RemoveChildren(void); CString GetAttribute( CString strName, LPCTSTR lpszDefault = NULL) const; bool GetAttribute( CString strName, bool bDefault) const; int GetAttribute( CString strName, int nDefault) const; long GetAttribute( CString strName, long lDefault) const; __int64 GetAttribute( CString strName, __int64 llDefault) const; float GetAttribute( CString strName, float fDefault) const; double GetAttribute( CString strName, double dDefault) const; DWORD GetAttribute( CString strName, DWORD dwDefault) const; BOOL SetAttribute( CString strName, LPCTSTR lpszValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL SetAttribute( CString strName, bool bValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL SetAttribute( CString strName, int nValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL SetAttribute( CString strName, long lValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL SetAttribute( CString strName, __int64 llValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL SetAttribute( CString strName, float fValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL SetAttribute( CString strName, double dValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL SetAttribute( CString strName, DWORD dwValue , CString strPrefix = _T(""), CString strNamespaceURI = _T("")); BOOL RemoveAttribute( CString strName ); CString GetValue( LPCTSTR lpszDefault = NULL ) const; bool GetValue( bool bDefault ) const; int GetValue( int nDefault) const; long GetValue( long lDefault) const; __int64 GetValue( __int64 llDefault) const; float GetValue( float fDefault) const; double GetValue( double dDefault) const; DWORD GetValue( DWORD dwDefault) const; BOOL SetValue( LPCTSTR lpszValue ); BOOL SetValue( bool bValue ); BOOL SetValue( int nValue ); BOOL SetValue( long lValue ); BOOL SetValue( __int64 llValue ); BOOL SetValue( float fValue ); BOOL SetValue( double dValue ); BOOL SetValue( DWORD dwValue ); CXmlNodePtr SelectSingleNode(LPCTSTR lpszPath); CXmlNodesPtr SelectNodes(LPCTSTR lpszPath); CString GetOuterXml(void) const; CString GetInnerXml(void) const; }; CXmlNodes class CXmlNodes { friend class CXml; friend class CXmlNode; friend class CXmlNodes; public: ~CXmlNodes(void); CXmlNodes(void); CXmlNodes( const CXmlNodes & refNodes ); CXmlNodes( CXmlNodesPtr pNodes ); CXmlNodesPtr operator = (CXmlNodesPtr pNodes); CXmlNodes & operator = (const CXmlNodes & refNodes); CXmlNodePtr operator[] ( LONG lIndex ); CXmlNodePtr operator[] ( LPCTSTR lpszName ); LONG GetCount(void); void Release(void); CXmlNodePtr GetItem( LONG nIndex ); CXmlNodePtr GetItem( LPCTSTR lpszName ); protected: CXmlNodes(MSXML2::IXMLDOMNodeListPtr pNodeList); MSXML2::IXMLDOMNodeListPtr m_pNodeList; }; CXsl class CXsl { public: CXsl(void); ~CXsl(void); // Open XSL file BOOL Open(LPCTSTR lpszXslFilePath); // close XSL file void Close(void); // transform to file BOOL TransformToFile( CXml & objXml, LPCTSTR lpszFilePath); // add a parameter BOOL AddParameter( LPCTSTR lpszParamName, LPCTSTR lpszParamValue, LPCTSTR lpszNamespaceURI = NULL); protected: MSXML2::IXSLTemplatePtr m_pIXSLTemplate; MSXML2::IXMLDOMDocument2Ptr m_pStyleSheet; MSXML2::IXSLProcessorPtr m_pIXSLProcessor; }; History v2.0 Created: 2007-07-16 v2.1 Added LoadXml method Added GetVersion method Added const for GetXXX methods Defined ASSERT as ATLASSERT for ATL Defined TRACE as ATLTRACE for ATL V2.2 Added the parameter lpszRootName for CXml::Open Removed CXml::GetLastError Added CXml::AddNamespace Added two new overrides for CXml::CreateNode with namespace support V3.0 Added another copy constructor for CXmlNode and CXmlNodes Added const modifier for some variables Added CXmlNode::GetInnerXml Added CXmlNode::GetOuterXml Added CXml::Create Changed the MSXML version for Create to 6.0 -> 3.0 -> 5.0 -> 4.0 Added namespace support for attributes Added a new class named CXsl V3.1 Add method CXml::SaveWithFormatted (Thanks to roel_) Reuse CXml::SaveStreamToFile in CXsl::TransformToFile Add CXsl::AddParameter to allow passing parameters to XSLT Use std::tr1::shared_ptr if exists instead of std::auto_ptr Change namespace from Generic to JWXml V3.2 Bug fix for the Create method usage in demo. Upgrade to VS2010 Download source (version 3.0) Download source (version 3.1) Download source (version 3.2) http://www.codeproject.com/Articles/19624/CXml-A-Wrapping-Class-for-MSXML-3-0-4-0-5-0-6-0
-
Megashares - Drag. Drop. Yup. The first site to provide FREE file hosting with drag n drop support.
-
reUP
-
Scanning result Download it Print with tool : Source : Imports System.Xml Imports System.IO Public Class Form1 Private Sub btn_resolve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_resolve.Click GetIPInfo(txt_IPAddress.Text) End Sub Public Sub GetIPInfo(ByVal IP As String) Dim resolver As New XmlUrlResolver() Dim myUri As New Uri("http://freegeoip.appspot.com/xml/" & IP) Dim s As Stream = DirectCast(resolver.GetEntity(myUri, Nothing, GetType(Stream)), Stream) ' Construct a reader using the Stream object. Dim xmlTextReader As New XmlTextReader(s) Dim xdoc1 As New XmlDataDocument() xdoc1.DataSet.ReadXml(xmlTextReader, XmlReadMode.Auto) Dim ds As DataSet = xdoc1.DataSet 'DG_LiveRates.DataSource = xdoc1.DataSet; 'DataSet ds = new DataSet(); Dim dt As DataTable = ds.Tables(0) DG_IPInfo.DataSource = dt End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load lbl_myip.Text = GetIP.GetExternalIp() End Sub End Class Sorry pentru treaba cu " ping www.rstcenter.com " era doar pentru demonstratie , am pus consola CMD peste date .
-
Introduction If you're new to UDP, I suggest you reading UDP Send and Receive using threads in VB.NET - CodeProject by Kumudu Gunasekara. I used his work as a take-off point, and wish to thank him. There's also a TinyUDP - Simple UDP Client/Server Components for .NET - CodeProject article on Code Project, which also looks very promising. What I'm doing here is going a bit more in depth, to show a possible way of UDP communication. As you may already heard UDP is well-know as "unreliable" protocol. Unreliable means that you have no guarantees that the packets you send will ever reach their destination. UDP also doesn't guarantees that individual packets of a transmission will arrive in the same order they were sent. There is also a problem of duplicate messages (you sent 1 and 3 arrived, woah!). If any kind of reliability for the information transmited is needed, it must be implemented in upper layers - i.e. in your application. So your first task as UDP coder is to design a low-level protocol, which will be handling datagram transfers for you. Two things it must do: ensure delivery and ensure delivery-in-correct-order. On top of that protocol you may later add a protocol for actual communications (i.e. chat message commands, nickname changes, etc). I do not recommend you to use my code in your real-world client/server applications. Just see how it works (not too good at times!) and build a better one. Protocols As mentioned before, this design uses 2 protocols, low-level or delivery protocol for datagram transmissions and and high-level or actual protocol for application communications. Both protocols benefit from BinNumerization proccess, which I must explain before we go on. BinNum, UnBinNum and packet delimiting Imagine a task: transfer 2 vairables A and B (they containt numbers 34 and 257) over a network. What are the possible ways to do this? ASCII. Encode like this (most common way): 34|257 Numbers are delimited by a special ASCII character, called.. delimiter. Some times CrLf is used for such purpose. The main downfall of this method is a guy, who comes to your chat with a name like 'TheE||vis' . And even more serious problem lies in a sphere of file transfer. Binary files tend to use all kind of bytes in them, you know. Delimiting is the most obious way to do things, and because of that, I strongly recommend avoiding it. Encode like this (sometimes used in ASCII protocols): 0003400257 Each number uses 5 digits to represent itself and adds trailing zeros. This way, dividing the string into 2 parts will give you 00034 and 00257. Downfalls: you lose some bytes on stupid zeros. Encode like this : 2.343.257 What's actually going on here is a length of string representing your number delimited from the actual number with an ASCII character. This way, parser reads up everything you need before the dot (will get "2"), then eats out exactly 2 characters ("34"), which will leave him with a "3.257" string, and all he has to do is.. repeat. By the way, if you're developing a protocol, consider the above scheme! This is ofcourse more imortant on TCP, where the packets are streamed and cutting/fitting chunks is a number one priority. Binary. That's easy. Each number is encoded as a byte. Or as a word. This is almost a perfect way to transfer data. The only downfall of which is: I can encode 34 into a byte, but have no way to fit 257 into a byte, so, I have to use a word for it. If variable B (257) becomes 255 someday, it will spare 3 extra bytes for it's word encoding. BinNumerization. This method requires some work on the sending and receiving sides, but NEVER spares even a single byte with unnessecery data. The number is encoded as byte, if it is below 248 and as a string with it's length added if it's above. 255-248 = 7 digit numbers maximum. You can adjust those values for your needs. But be sure to do this on both sides! Public Function UnBinNum(ByRef S$, Optional ByVal EatOut As Boolean = True) As Integer 'MsgBox("CALL FOR UNBIN NUM:" & S$) Dim l As Int16 Dim nval As Long Dim h As String 'On Error GoTo Error If Asc(Left(S$, 1)) < 249 Then nval = Asc(Left(S$, 1)) If EatOut = True Then S$ = Right$(S$, Len(S$) - 1) Else l = Asc(Left$(S$, 1)) - 248 h = Mid$(S$, 2, l) If Len(S$) < l + 1 Then nval = -1 : GoTo ErrorS 'Debug.Print "len: " & l 'Debug.Print "hex:" & h 'Debug.Print "unhex:" & HexToDecimal(h) nval = HexToDecimal(h) If EatOut = True Then S$ = Right$(S$, Len(S$) - l - 1) End If ErrorS: 'MsgBox("nval:" & nval) Return CInt(nval) End Function Function BinNum(ByVal NUM) As String Dim h As String, l As Byte If NUM > 248 Then h = Hex(NUM) l = Len(h) + 248 If l > 255 Then MsgBox("L:" & l & "...." & h & "..." & Len(h)) Return (Chr(l) & h) Else Return (Chr(NUM)) End If End Function Yeah, I use those 2 in VB6 too. They also rely on HexToDecimal function found in the source (written not by me). Also note, that UnBinNum takes it's argument ByRef!Anyways, this implementation is not perfect (one of the downfalls is that you can't use negative numbers), but should give you a fair idea and prove, that the concept IS perfect. Well, at least almost: you still lose some bytes when encoding numbers in range 249-255 (they are encoded as strings, not as bytes). LOW-Level Delivery Protocol Each packet begins with 2 bytes and 1 BinNum representing the ClientID, PacketType and Sequence. The rest is a HIGH-level data and shouldn't be used on a low level. All three are vital. Since there is no way to determine a single connection in UDP (all you have to deal with is: IP, PORT, DATA that came) clientID comes in place. On my server example IP+ClientID form a unique client, while IP+Port are only used while there's no ClientID at all. But that happens only during the handshake. Handshake Client begins to transmit the NIL packet (made of three empty bytes, or 2 empty bytes and 1 empty BinNum, which is the same at the moment). Basicly client is saying: I'm new client, no ClientID, no transmission history, no previous experience, please give me a ClientID, I could work with. The server assigns a new ClientID to a pair of IP+port, and sends a welcoming message (one from the high level protocol). PacketTypes & Delivery The most usefull PacketType is INF (byte 2). It suggests a real data inside. With each INF received, receiver should send back the packet with type ACK (byte 0) or BUF (byte 1) which mean basicly the same: PACKET RECEIVED, DO NOT RESEND. The sender keeps sending the INF from the queue until it gets an ACK (or a BUF). What is the differnce between ACK and BUF you ask? BUF is sent whenever the packet is out of sequence (too old or came from the future), and might be not implemented by your client (if you have no buffering mechanism), but the receiver MUST ACK every incoming packet. 'Sending side Function Compose(ByVal RAWDATA as String) 'increment counter outSeq += 1 'add header RAWdata = Chr(clientID) & Chr(typ) & BinNum(outSeq) & RAWdata Dim dlg As New UDPMaster.DGram dlg.IP = IP dlg.Port = port dlg.data = UDPMaster.StringToBytes(RAWdata) 'add to sending buffer sendBuffer.Add(dlg) End Function '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' the sending side then loops through sendbuffer and sends it '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 'Receiving side Function CollectData() ' read Header ' byte(0) - clientID, byte(1) - type, UnBinNum (seqNum) If seqNum = mCl.inSeq Then ' ONE WE WAITED FOR udp.Send(mCl.IP, mCl.port, mCl.ComposeACK) 'ACK immidiatly 'increment the counter mCl.inSeq += 1 End if End Function ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' the sending side now receives an ACK and removes packet ' from sendBuffer ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' There is also a 255 or TERMINATION PacketType, which is sent upon disconnection. It is not mandatory, cause UDP is connection-less, and applications usually know their ways to tell disconnected clients (i.e. long time without a single ACK, or a simple ping time out). Each packet you queue to send is assigned a Sequnence number, which increases with every such action. Your ClientID as also packed inside the header as the first byte. The PacketType is INF, ACK or BUF. Only INF packets contan actual data, the rest are for signaling and managment. Reconnection. Server could send a NIL packet to the client, which means, that they have to perform a handshake again. This option should be used after a long disconnection time. HIGH-level actual protocol Nothing fancy here. It's mostly ASCII, with simple uppercased words as commands. Availible commands are "WHO" to list all connected clients, "SAY text" to transmit said text to everyone, and "FILE filename" to request a file transfer. The Code I've extracted the most generic bit to a UDPMaster class, which can serve both as a client and a server. UDPMaster also contains DGram class which is a structure to hold incoming datagrams. Here's how you use it to make a client (OR! a server). Dim udp as new UDPMaster(2002) ' local port you are listening too Do If udp.hasnews then 'Receive data Dim dgram as UPDMaster.Dgram udp.poll(dgram) 'Show data Console.WriteLine ("DATAGRAM received ") ; Console.WriteLine ("Sender: " & dgram.IP & ":" & dgram.port) 'the data is holded in dgram.data() byte array 'Work with data... ' ........... end if 'Send data... udp.send(drgam.IP, dgram.port, "REPLY") Loop Both client and the server are built on top of that code, but that's it. The UDPMaster does not contain any of the protocol specific features described above. It just reports new datagrams (or sends yours). Working with packets, deciding which goes to where, buffering them and acknowledging - all that is done on a higher level. The other class shared by both programs is client class. No particular reason for this, it was just convnient to use: this class stores IP, data, ping times etc, of 1 given client, so instead of declaring all those variables on the client side, I just stole the class from the server and declared a single instance. This makes files UDPMaster.vb and Helper.vb, found in both sollutions, identical. I've left alot of comments, but they more point to something, then explain anything (my comment righting skills are very low). To get a better understanding of what is going on you may uncomment all of those <code>BetCon</code> lines, they do the reporting to the console. Pressure control Only implement at server and should ONLY be seen as TEST-DEMO-DIRECTION-ETC. The pressure parameter (each client has one) is an ammount of ticks (1/1000 of second) the server will wait for ACK before retransmitting the data. Lowering this value will increase the pressure and the ammount of packets sent. Slow start I've tried to implement a slow start method (as seen in TCP), but with not much luck. The default pressure is 1000, which is then reduced to a suitable value, depending on packetloss. Packetloss The calculation of packetloss is made every 10 packet sends. The server divides ammount of sent packets to the ammount of received ACKs. If packet loss is high it will reduce pressure, and vice versa. Round trip times Time it takes for a packet to travel to it's destination and back. Calcualted by 2 timestamps (sent, received). This value should be aproximated (that's what gurus suggest), and that's exactly what those commented lines of code do (found in Done method of Client class) I hope, you'll be able to build a desent pressure control system, cause I kinda failed on that task. If you're really up to this task, try reading TCP/IP RFCs, they provide alot of intersting techniques. Download source Download project demo http://www.codeproject.com/Articles/13935/Building-a-UDP-Client-Server-application-in-VB-NET