Search Results

Search found 373 results on 15 pages for 'payload'.

Page 4/15 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Possible to IPSec VPN Tunnel Public IP Addresses?

    - by caleban
    A customer uses an IBM SAS product over the internet. Traffic flows from the IBM hosting data center to the customer network through Juniper VPN appliances. IBM says they're not tunneling private IP addresses. IBM says they're tunneling public IP addresses. Is this possible? What does this look like in the VPN configuration and in the packets? I'd like to know what the source/destination ip/ports would look like in the encrypted tunneled IPSec Payload and in the IP packet carrying the IPSec Payload. IPSec Payload: source:1.1.1.101:1001 destination:2.2.2.101:2001 IP Packet: source:1.1.1.1:101 destination:2.2.2.1:201 Is it possible to send public IP addresses through an IPSec VPN tunnel? Is it possible for IBM to send a print job from a server on their network using the static-nat public address over a VPN to a printer at a customer network using the printer's static-nat public address? Or can a VPN not do this? Can a VPN only work with interesting traffic from and to private IP addresses?

    Read the article

  • What is the "in-the-wire" size of a ethernet frame? 1518 or 1542?

    - by chrisapotek
    According to the table here, it says that MTU = 1500 bytes and that the payload part is 1500 - 42 bytes or 1458 bytes (<- this is actually wrong!). Now on top of that you have to add IPv4 and UDP headers, which are 28 bytes (20 IP + 8 UDP). That leaves my maximum possible application message to as 1430 bytes! But by looking for this number in the Internet I see 1472 instead. Am I doing this calculation wrong here? All I want to find out is the maximum application message I can send over the wire without the risk of fragmentation. It is definitely not 1500 because that includes the frame headers. Can someone help? The confusion is the the PAYLOAD can actually be as large as 1500 bytes and that's the MTU. So now what is the size in-the-wire for a payload of 1500? From that table it can be as big as 1542 bytes. So the maximum app messages I can send is 1472 (1500 - 20 (ip) - 8 (udp)) for a maximum in the wire size of 1542. It amazes me how things can get so complicated when they are actually simple. And I have not clue how someone came up with the number 1518 if the table says 1542.

    Read the article

  • Bad performance with Linux software RAID5 and LUKS encryption

    - by Philipp Wendler
    I have set up a Linux software RAID5 on three hard drives and want to encrypt it with cryptsetup/LUKS. My tests showed that the encryption leads to a massive performance decrease that I cannot explain. The RAID5 is able to write 187 MB/s [1] without encryption. With encryption on top of it, write speed is down to about 40 MB/s. The RAID has a chunk size of 512K and a write intent bitmap. I used -c aes-xts-plain -s 512 --align-payload=2048 as the parameters for cryptsetup luksFormat, so the payload should be aligned to 2048 blocks of 512 bytes (i.e., 1MB). cryptsetup luksDump shows a payload offset of 4096. So I think the alignment is correct and fits to the RAID chunk size. The CPU is not the bottleneck, as it has hardware support for AES (aesni_intel). If I write on another drive (an SSD with LVM) that is also encrypted, I do have a write speed of 150 MB/s. top shows that the CPU usage is indeed very low, only the RAID5 xor takes 14%. I also tried putting a filesystem (ext4) directly on the unencrypted RAID so see if the layering is problem. The filesystem decreases the performance a little bit as expected, but by far not that much (write speed varying, but 100 MB/s). Summary: Disks + RAID5: good Disks + RAID5 + ext4: good Disks + RAID5 + encryption: bad SSD + encryption + LVM + ext4: good The read performance is not affected by the encryption, it is 207 MB/s without and 205 MB/s with encryption (also showing that CPU power is not the problem). What can I do to improve the write performance of the encrypted RAID? [1] All speed measurements were done with several runs of dd if=/dev/zero of=DEV bs=100M count=100 (i.e., writing 10G in blocks of 100M). Edit: If this helps: I'm using Ubuntu 11.04 64bit with Linux 2.6.38. Edit2: The performance stays approximately the same if I pass a block size of 4KB, 1MB or 10MB to dd.

    Read the article

  • Using u32 together with extension headers (how to jump over them?)

    - by bortzmeyer
    I'm trying to filter on some parts of the payload, for an IPv6 packet with extension headers (for instance Destination Options). ip6tables works fine with conditions like --proto udp or --dport 109, even when the packet has extension headers. Netfilter clearly knows how to jump over Destination Options to find the UDP header. Now, I would like to use the u32 module to match a byte in the payload (say "I want the third byte of the payload to be 42). If the packet has no extension headers something like --u32 "48&0x0000ff00=0x2800"` (48 = 40 bytes for the IPv6 header + 8 for the UDP header) works fine, If the packet has a Destination Options, it no longer matches. I would like to write a rule that will work whether the packet has Destination Options or not. I do not find a way to tell Netfilter to parse until the UDP header (something that it is able to do, otherwise --dport 109 would not work) then to leave u32 parse the rest. I'm looking for a simple way, otherwise, as BatchyX mentions, I could write a kernel module doing what I want.

    Read the article

  • Why is "wsdl" namespace interjected into action name when using savon for ruby soap communication?

    - by Nick Gorbikoff
    I'm trying to access a SOAP service i don't control. One of the actions is called ProcessMessage. I follow example and generate a SOAP request, but I get an error back saying that the action doesn't exist. I traced the problem to the way the body of the envelope is generated. <env:Envelope ... "> <env:Header> <wsse:Security ... "> <wsse:UsernameToken ..."> <wsse:Username>USER</wsse:Username> <wsse:Nonce>658e702d5feff1777a6c741847239eb5d6d86e48</wsse:Nonce> <wsu:Created>2010-02-18T02:05:25Z</wsu:Created> <wsse:Password ... >password</wsse:Password> </wsse:UsernameToken> </wsse:Security> </env:Header> <env:Body> <wsdl:ProcessMessage> <payload> ...... </payload> </wsdl:ProcessMessage> </env:Body> </env:Envelope> That ProcessMessage tag should be : <ProcessMessage xmlns="http://www.starstandards.org/webservices/2005/10/transport"> That's what it is when it is generated by the sample java app, and it works. That tag is the only difference between what my ruby app generates and the sample java app. Is there any way to get rid of the "wsdl:" namesaplce in front of that one tag and add an attribute like that. Barring that, is there a way to make force the action to be not to be generated by just passed as a string like the rest of the body? Here is my code. require 'rubygems' require 'savon' client = Savon::Client.new "https://gmservices.pp.gm.com/ProcessMessage?wsdl" response = client.process_message! do | soap, wsse | wsse.username = "USER" wsse.password = "password" soap.namespace = "http://www.starstandards.org/webservices/2005/10/transport" #makes no difference soap.action = "ProcessMessage" #makes no difference soap.input = "ProcessMessage" #makes no difference #my body at this point is jsut one big xml string soap.body = "<payload>...</payload>" # putting <ProccessMessage> tag here doesn't help as it just creates a duplicate tag in the body, since Savon keeps interjecting <wsdl:ProcessMessage> tag. end Thank you P.S.: I tried handsoap but it doesn't support httpS and is confusing, and I tried soap4r but but it'even more confusing than handsoap.

    Read the article

  • Reconstructing data from PCAP sniff

    - by Ishi
    Hi everyone !! I am trying to sniff HTTP data through libpcap and get all the http contents (header+payload) after processing the TCP payload. As per my discussion at http://stackoverflow.com/questions/2905430/writing-an-http-sniffer-or-any-other-application-level-sniffer , I am facing problems due to fragmentation - I need to reconstruct the whole stream (or defragment it) to get a complete HTTP packet, and this is where I need some help. Thanks in anticipation !!

    Read the article

  • Java object to XML Elements?

    - by DaveKub
    I'm working on a webservices client app and I have it mostly working. I can retrieve and read data from the third-party webservice fine. Now I need to submit some data and I'm stuck. The classes for the objects I'm retrieving/submitting were generated from XSD files via the xjc tool. The part I'm stuck on is turning one of those objects into an XML tree to submit to the webservice. When I retrieve/send a request from/to the ws, it contains a 'payload' object. This is defined in java code as (partial listing): @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PayloadType", propOrder = { "compressed", "document", "any", "format" }) public class PayloadType { @XmlElement(name = "Compressed") protected String compressed; @XmlElement(name = "Document") protected List<String> document; @XmlAnyElement protected List<Element> any; protected String format; public List<Element> getAny() { if (any == null) { any = new ArrayList<Element>(); } return this.any; } } The only field I'm concerned with is the 'any' field which contains an XML tree. When I retrieve data from the ws, I read that field with something like this: ('root' is of org.w3c.dom.Element type and is the result of calling 'getAny().get(0)' on the payload object) NodeList nl = root.getElementsByTagName("ns1:Process"); // "ns1:Process" is an XML node to do something with if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { Element proc = (Element) nl.item(i); try { // do something with the 'proc' Element here... } catch (Exception ex) { // handle problems here... } } } Submitting data is where I'm stuck. How do I take a java object created from one of the classes generated from XSD and turn it into an Element object that I can add to the 'any' List of the payload object?? For instance, if I have a DailyData class and I create and populate it with data: DailyData dData = new DailyData(); dData.setID = 34; dData.setValues = "3,5,76,23"; How do I add that 'dData' object to the 'any' List of the payload object? It has to be an Element. Do I do something with a JAXBContext marshaller? I've used that to dump the 'dData' object to the screen to check the XML structure. I'm sure the answer is staring me in the face but I just can't see it! Dave

    Read the article

  • Apple Push Notifications With Foreign Accent Characters Not Receiving

    - by confeng
    I'm sending push notifications and when the message contains foreign characters (Turkish in my case) like I, s, ç, g... The message does not arrive to devices. Here's my code: $message = 'THIS is push'; $passphrase = 'mypass'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'MyPemFile.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client( 'ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL); echo 'Connected to Apple service. ' . PHP_EOL; // Encode the payload as JSON $body['aps'] = array( 'alert' => $message, 'sound' => 'default' ); $payload = json_encode($body); $result = 'Start'.PHP_EOL; $tokenArray = array('mytoken'); foreach ($tokenArray as $item) { // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) echo 'Failed message'.PHP_EOL; else echo 'Successful message'.PHP_EOL; } // Close the connection to the server fclose($fp); I have tried encoding $message variable with utf8_encode() but the message received as "THÝS is push". And other ways like iconv() didn't work for me, some of them cropped Turkish characters, some didn't receive at all. I also have header('content-type: text/html; charset: utf-8'); and <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> in my page. I don't think the problem appears while I set the value but maybe with pack() function. Any ideas to solve this without replacing characters with English?

    Read the article

  • Site-to-site VPN using MD5 instead of SHA and getting regular disconnection

    - by Steven
    We are experiencing some strange behavior with a site-to-site IPsec VPN that goes down about every week for 30 minutes (Iam told 30 minutes exactly). I don't have access to the logs, so it's difficult to troubleshoot. What is also strange is that the two VPN devices are set to use SHA hash algorithm but apparently end up agreeing to use MD5. Does anybody have a clue? or is this just insufficient information? Edit: Here is an extract of the log of one of the two VPN devices, which is a Cisco 3000 series VPN concentrator. 27981 03/08/2010 10:02:16.290 SEV=4 IKE/41 RPT=16120 xxxxxxxx IKE Initiator: New Phase 1, Intf 2, IKE Peer xxxxxxxx local Proxy Address xxxxxxxx, remote Proxy Address xxxxxxxx, SA (L2L: 1A) 27983 03/08/2010 10:02:56.930 SEV=4 IKE/41 RPT=16121 xxxxxxxx IKE Initiator: New Phase 1, Intf 2, IKE Peer xxxxxxxx local Proxy Address xxxxxxxx, remote Proxy Address xxxxxxxx, SA (L2L: 1A) 27986 03/08/2010 10:03:35.370 SEV=4 IKE/41 RPT=16122 xxxxxxxx IKE Initiator: New Phase 1, Intf 2, IKE Peer xxxxxxxx local Proxy Address xxxxxxxx, remote Proxy Address xxxxxxxx, SA (L2L: 1A) [… same continues for another 15 minutes …] 28093 03/08/2010 10:19:46.710 SEV=4 IKE/41 RPT=16140 xxxxxxxx IKE Initiator: New Phase 1, Intf 2, IKE Peer xxxxxxxx local Proxy Address xxxxxxxx, remote Proxy Address xxxxxxxx, SA (L2L: 1A) 28096 03/08/2010 10:20:17.720 SEV=5 IKE/172 RPT=1291 xxxxxxxx Group [xxxxxxxx] Automatic NAT Detection Status: Remote end is NOT behind a NAT device This end IS behind a NAT device 28100 03/08/2010 10:20:17.820 SEV=3 IKE/134 RPT=79 xxxxxxxx Group [xxxxxxxx] Mismatch: Configured LAN-to-LAN proposal differs from negotiated proposal. Verify local and remote LAN-to-LAN connection lists. 28103 03/08/2010 10:20:17.820 SEV=4 IKE/119 RPT=1197 xxxxxxxx Group [xxxxxxxx] PHASE 1 COMPLETED 28104 03/08/2010 10:20:17.820 SEV=4 AUTH/22 RPT=1031 xxxxxxxx User [xxxxxxxx] Group [xxxxxxxx] connected, Session Type: IPSec/LAN- to-LAN 28106 03/08/2010 10:20:17.820 SEV=4 AUTH/84 RPT=39 LAN-to-LAN tunnel to headend device xxxxxxxx connected 28110 03/08/2010 10:20:17.920 SEV=5 IKE/25 RPT=1291 xxxxxxxx Group [xxxxxxxx] Received remote Proxy Host data in ID Payload: Address xxxxxxxx, Protocol 0, Port 0 28113 03/08/2010 10:20:17.920 SEV=5 IKE/24 RPT=88 xxxxxxxx Group [xxxxxxxx] Received local Proxy Host data in ID Payload: Address xxxxxxxx, Protocol 0, Port 0 28116 03/08/2010 10:20:17.920 SEV=5 IKE/66 RPT=1290 xxxxxxxx Group [xxxxxxxx] IKE Remote Peer configured for SA: L2L: 1A 28117 03/08/2010 10:20:17.930 SEV=5 IKE/25 RPT=1292 xxxxxxxx Group [xxxxxxxx] Received remote Proxy Host data in ID Payload: Address xxxxxxxx, Protocol 0, Port 0 28120 03/08/2010 10:20:17.930 SEV=5 IKE/24 RPT=89 xxxxxxxx Group [xxxxxxxx] Received local Proxy Host data in ID Payload: Address xxxxxxxx, Protocol 0, Port 0 28123 03/08/2010 10:20:17.930 SEV=5 IKE/66 RPT=1291 xxxxxxxx Group [xxxxxxxx] IKE Remote Peer configured for SA: L2L: 1A 28124 03/08/2010 10:20:18.070 SEV=4 IKE/173 RPT=17330 xxxxxxxx Group [xxxxxxxx] NAT-Traversal successfully negotiated! IPSec traffic will be encapsulated to pass through NAT devices. 28127 03/08/2010 10:20:18.070 SEV=4 IKE/49 RPT=17332 xxxxxxxx Group [xxxxxxxx] Security negotiation complete for LAN-to-LAN Group (xxxxxxxx) Responder, Inbound SPI = 0x56a4fe5c, Outbound SPI = 0xcdfc3892 28130 03/08/2010 10:20:18.070 SEV=4 IKE/120 RPT=17332 xxxxxxxx Group [xxxxxxxx] PHASE 2 COMPLETED (msgid=37b3b298) 28131 03/08/2010 10:20:18.750 SEV=4 IKE/41 RPT=16141 xxxxxxxx Group [xxxxxxxx] IKE Initiator: New Phase 2, Intf 2, IKE Peer xxxxxxxx local Proxy Address xxxxxxxx, remote Proxy Address xxxxxxxx, SA (L2L: 1A) 28135 03/08/2010 10:20:18.870 SEV=4 IKE/173 RPT=17331 xxxxxxxx Group [xxxxxxxx] NAT-Traversal successfully negotiated! IPSec traffic will be encapsulated to pass through NAT devices.

    Read the article

  • Client side code snipets

    - by raghu.yadav
    function clientMethodCall(event) { component = event.getSource(); AdfCustomEvent.queue(component, "customEvent",{payload:component.getSubmittedValue()}, true); event.cancel(); } ]]-- <af:document>      <f:facet name="metaContainer">      <af:group>        <!--[CDATA[            <script>                function clientMethodCall(event) {                                       component = event.getSource();                    AdfCustomEvent.queue(component, "customEvent",{payload:component.getSubmittedValue()}, true);                                                     event.cancel();                                    }                 </script> ]]-->      </af:group>    </f:facet>      <af:form>        <af:panelformlayout>          <f:facet name="footer">          <af:inputtext label="Let me spy on you: Please enter your mail password">            <af:clientlistener method="clientMethodCall" type="keyUp">            <af:serverlistener type="customEvent" method="#{customBean.handleRequest}">          </af:serverlistener>bean code    public void handleRequest(ClientEvent event){                System.out.println("---"+event.getParameters().get("payload"));            } tree<af:tree id="tree1" value="#{bindings.DepartmentsView11.treeModel}" var="node" selectionlistener="#{bindings.DepartmentsView11.treeModel.makeCurrent}" rowselection="single">    <f:facet name="nodeStamp">      <af:outputtext value="#{node}">    </af:outputtext>    <af:clientlistener method="expandNode" type="selection">  </af:clientlistener></f:facet>   <f:facet name="metaContainer">        <af:group>          <!--[CDATA[            <script>                function expandNode(event){                    var _tree = event.getSource();                    rwKeySet = event.getAddedSet();                    var firstRowKey;                    for(rowKey in rwKeySet){                       firstRowKey  = rowKey;                        // we are interested in the first hit, so break out here                        break;                    }                    if (_tree.isPathExpanded(firstRowKey)){                         _tree.setDisclosedRowKey(firstRowKey,false);                    }                    else{                        _tree.setDisclosedRowKey(firstRowKey,true);                    }               }        </script> ]]-->        </af:group>      </f:facet>   </af:tree> </af:clientlistener></af:inputtext></f:facet></af:panelformlayout></af:form></af:document> bean code public void handleRequest(ClientEvent event){ System.out.println("---"+event.getParameters().get("payload")); } tree function expandNode(event){ var _tree = event.getSource(); rwKeySet = event.getAddedSet(); var firstRowKey; for(rowKey in rwKeySet){ firstRowKey = rowKey; // we are interested in the first hit, so break out here break; } if (_tree.isPathExpanded(firstRowKey)){ _tree.setDisclosedRowKey(firstRowKey,false); } else{ _tree.setDisclosedRowKey(firstRowKey,true); } } ]]--

    Read the article

  • WIF-less claim extraction from ACS: JWT

    - by Elton Stoneman
    ACS support for JWT still shows as "beta", but it meets the spec and it works nicely, so it's becoming the preferred option as SWT is losing favour. (Note that currently ACS doesn’t support JWT encryption, if you want encrypted tokens you need to go SAML). In my last post I covered pulling claims from an ACS token without WIF, using the SWT format. The JWT format is a little more complex, but you can still inspect claims just with string manipulation. The incoming token from ACS is still presented in the BinarySecurityToken element of the XML payload, with a TokenType of urn:ietf:params:oauth:token-type:jwt: <t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">   <t:Lifetime>     <wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2012-08-31T07:39:55.337Z</wsu:Created>     <wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2012-08-31T09:19:55.337Z</wsu:Expires>   </t:Lifetime>   <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">     <EndpointReference xmlns="http://www.w3.org/2005/08/addressing">       <Address>http://localhost/x.y.z</Address>     </EndpointReference>   </wsp:AppliesTo>   <t:RequestedSecurityToken>     <wsse:BinarySecurityToken wsu:Id="_1eeb5cf4-b40b-40f2-89e0-a3343f6bd985-6A15D1EED0CDB0D8FA48C7D566232154" ValueType="urn:ietf:params:oauth:token-type:jwt" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">[ base64string ] </wsse:BinarySecurityToken>   </t:RequestedSecurityToken>   <t:TokenType>urn:ietf:params:oauth:token-type:jwt</t:TokenType>   <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>   <t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType> </t:RequestSecurityTokenResponse> The token as a whole needs to be base-64 decoded. The decoded value contains a header, payload and signature, dot-separated; the parts are also base-64, but they need to be decoded using a no-padding algorithm (implementation and more details in this MSDN article on validating an Exchange 2013 identity token). The values are then in JSON; the header contains the token type and the hashing algorithm: "{"typ":"JWT","alg":"HS256"}" The payload contains the same data as in the SWT, but JSON rather than querystring format: {"aud":"http://localhost/x.y.z" "iss":"https://adfstest-bhw.accesscontrol.windows.net/" "nbf":1346398795 "exp":1346404795 "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant":"2012-08-31T07:39:53.652Z" "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod":"http://schemas.microsoft.com/ws/2008/06/identity/authenticationmethod/windows" "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname":"xyz" "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress":"[email protected]" "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn":"[email protected]" "identityprovider":"http://fs.svc.x.y.z.com/adfs/services/trust"} The signature is in the third part of the token. Unlike SWT which is fixed to HMAC-SHA-256, JWT can support other protocols (the one in use is specified as the "alg" value in the header). How to: Validate an Exchange 2013 identity token contains an implementation of a JWT parser and validator; apart from the custom base-64 decoding part, it’s very similar to SWT extraction. I've wrapped the basic SWT and JWT in a ClaimInspector.aspx page on gitHub here: SWT and JWT claim inspector. You can drop it into any ASP.Net site and set the URL to be your redirect page in ACS. Swap ACS to issue SWT or JWT, and using the same page you can inspect the claims that come out.

    Read the article

  • Base 128 or 256 Encoding for the Binary Lexical Octet Adhoc Transport Protocol?

    - by Randolpho
    I'm in the process of implementing a network driver for the Binary Lexical Octet Adhoc Transport (BLOAT) protocols in the hopes of replacing the TCP/UDP/IP stack with a much more flexible XML structure. BLOAT is detailed in RFC 3252, so if you're unfamiliar with the protocol I highly recommend you read the entire RFC before providing any comments. Don't worry, it's short and sweet; you might even enjoy it. Anyway, my problem is this: BLOAT requires that the payload be Base64 encoded which doesn't make sense to me. I mean, sure, it's the internet standard for binary payloads, but there are better, more efficient encodings available: Base128 and Base256, for example. That the RFC requires Base64 and doesn't allow for any other payload encoding really bothers me. To that end, I'm considering a small optional change to the protocol. Embrace and extend, right? Anyway, I'd like to modify the payload element to accept an encoding attribute, which can extend the encoding to Base128 or Base256, or even to other encodings I can't conceive of at the moment. If the encoding attribute isn't present, Base64 would be assumed. So my question is this: should I? I mean, BLOAT is an accepted standard, even if it isn't exactly omnipresent. If I make this change, will there be compatibility issues? I don't foresee any, but perhaps you, oh great Stack Overflow Community, can? If I do implement this change, should I contact the original RFC author? Should I offer a supplemental RFC?

    Read the article

  • How to pass multiple different records (not class due to delphi limitations) to a function?

    - by mingo
    Hi to all. I have a number of records I cannot convert to classes due to Delphi limitation (all of them uses class operators to implement comparisons). But I have to pass to store them in a class not knowing which record type I'm using. Something like this: type R1 = record begin x :Mytype; class operator Equal(a,b:R1) end; type R2 = record begin y :Mytype; class operator Equal(a,b:R2) end; type Rn = record begin z :Mytype; class operator Equal(a,b:Rn) end; type TC = class begin x : TObject; y : Mytype; function payload (n:TObject) end; function TC.payload(n:TObject) begin x := n; end; program: c : TC; x : R1; y : R2; ... c := TC.Create(): n:=TOBject(x); c.payload(n); Now, Delphi do not accept typecast from record to TObject, and I cannot make them classes due to Delphi limitation. Anyone knows a way to pass different records to a function and recognize their type when needed, as we do with class: if x is TMyClass then TMyClass(x) ... ???

    Read the article

  • Is my method for avoiding dynamic_cast<> faster than dynamic_cast<> itself ?

    - by ereOn
    Hi, I was answering a question a few minutes ago and it raised to me another one: In one of my projects, I do some network message parsing. The messages are in the form of: [1 byte message type][2 bytes payload length][x bytes payload] The format and content of the payload are determined by the message type. I have a class hierarchy, based on a common class Message. To instanciate my messages, i have a static parsing method which gives back a Message* depending on the message type byte. Something like: Message* parse(const char* frame) { // This is sample code, in real life I obviously check that the buffer // is not NULL, and the size, and so on. switch(frame[0]) { case 0x01: return new FooMessage(); case 0x02: return new BarMessage(); } // Throw an exception here because the mesage type is unknown. } I sometimes need to access the methods of the subclasses. Since my network message handling must be fast, I decived to avoid dynamic_cast<> and I added a method to the base Message class that gives back the message type. Depending on this return value, I use a static_cast<> to the right child type instead. I did this mainly because I was told once that dynamic_cast<> was slow. However, I don't know exactly what it really does and how slow it is, thus, my method might be as just as slow (or slower) but far more complicated. What do you guys think of this design ? Is it common ? Is it really faster than using dynamic_cast<> ? Any detailed explanation of what happen under the hood when one use dynamic_cast<> is welcome !

    Read the article

  • getting attribute as column headers

    - by edwards
    I have the following XML: <DEVICEMESSAGES> <VERSION xml="1" checksum="" revision="0" envision="33050000" device="" /> <HEADER id1="0001" id2="0001" content="Nasher[&lt;messageid&gt;]: &lt;!payload&gt;" /> <MESSAGE level="7" parse="1" parsedefvalue="1" tableid="15" id1="24682" id2="24682" eventcategory="1003010000" content="Access to &lt;webpage&gt; was blocked due to its category (&lt;info&gt; by &lt;hostname&gt;)" /> </DEVICEMESSAGES> I am using the following XSLT: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="DEVICEMESSAGES/HEADERS"> <xsl:value-of select="@id2"/>,<xsl:text/> <xsl:value-of select="@content"/>,<xsl:text/> <xsl:text>&#xa;</xsl:text> </xsl:template> </xsl:stylesheet> I get the following output: 0001 , Nasher[<messageid>]: <!payload> whereas I need the column headings, too: id2, content 0001 , Nasher[<messageid>]: <!payload>

    Read the article

  • How frequently IP packets are fragmented at the source host?

    - by Methos
    I know that if IP payload MTU then routers usually fragment the IP packet. Finally all the fragmented packets are assembled at the destination using the fields IP-ID, IP fragment offsets and fragmentation flags. Max length of IP payload is 64K. Thus its very plausible for L4 to hand over payload which is 64K. If the L2 protocol is Ethernet, which often is the case, then the MTU will be about 1600 bytes. Hence IP packet will be fragmented at the source host itself. However, a quick search about IP implementation in Linux tells me that in recent kernels, L4 protocols are fragment friendly i.e. they try to save the fragmentation work for IP by handing over buffers of size which is close to MTU. Considering these two facts, I am wondering about how frequently does the IP packet gets fragmented at the source host itself. Does it occur sometimes/rarely/never? Does anyone know if there are exceptions to the rule of fragmentation in linux kernel (i.e. are there situations where L4 protocols are not fragment friendly)? How is this handled in other common OSes like windows? In general how frequently IP packets are fragmented?

    Read the article

  • Linux - Only first virtual interface can ping external gateway

    - by husvar
    I created 3 virtual interfaces with different mac addresses all linked to the same physical interface. I see that they successfully arp for the gw and they can ping (the request is coming in the packet capture in wireshark). However the ping utility does not count the responses. Does anyone knows the issue? I am running Ubuntu 14.04 in a VmWare. root@ubuntu:~# ip link sh 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 link/ether 00:0c:29:bc:fc:8b brd ff:ff:ff:ff:ff:ff root@ubuntu:~# ip addr sh 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 00:0c:29:bc:fc:8b brd ff:ff:ff:ff:ff:ff inet6 fe80::20c:29ff:febc:fc8b/64 scope link valid_lft forever preferred_lft forever root@ubuntu:~# ip route sh root@ubuntu:~# ip link add link eth0 eth0.1 addr 00:00:00:00:00:11 type macvlan root@ubuntu:~# ip link add link eth0 eth0.2 addr 00:00:00:00:00:22 type macvlan root@ubuntu:~# ip link add link eth0 eth0.3 addr 00:00:00:00:00:33 type macvlan root@ubuntu:~# ip -4 link sh 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 link/ether 00:0c:29:bc:fc:8b brd ff:ff:ff:ff:ff:ff 18: eth0.1@eth0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default link/ether 00:00:00:00:00:11 brd ff:ff:ff:ff:ff:ff 19: eth0.2@eth0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default link/ether 00:00:00:00:00:22 brd ff:ff:ff:ff:ff:ff 20: eth0.3@eth0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default link/ether 00:00:00:00:00:33 brd ff:ff:ff:ff:ff:ff root@ubuntu:~# ip -4 addr sh 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever root@ubuntu:~# ip -4 route sh root@ubuntu:~# dhclient -v eth0.1 Internet Systems Consortium DHCP Client 4.2.4 Copyright 2004-2012 Internet Systems Consortium. All rights reserved. For info, please visit https://www.isc.org/software/dhcp/ Listening on LPF/eth0.1/00:00:00:00:00:11 Sending on LPF/eth0.1/00:00:00:00:00:11 Sending on Socket/fallback DHCPDISCOVER on eth0.1 to 255.255.255.255 port 67 interval 3 (xid=0x568eac05) DHCPREQUEST of 192.168.1.145 on eth0.1 to 255.255.255.255 port 67 (xid=0x568eac05) DHCPOFFER of 192.168.1.145 from 192.168.1.254 DHCPACK of 192.168.1.145 from 192.168.1.254 bound to 192.168.1.145 -- renewal in 1473 seconds. root@ubuntu:~# dhclient -v eth0.2 Internet Systems Consortium DHCP Client 4.2.4 Copyright 2004-2012 Internet Systems Consortium. All rights reserved. For info, please visit https://www.isc.org/software/dhcp/ Listening on LPF/eth0.2/00:00:00:00:00:22 Sending on LPF/eth0.2/00:00:00:00:00:22 Sending on Socket/fallback DHCPDISCOVER on eth0.2 to 255.255.255.255 port 67 interval 3 (xid=0x21e3114e) DHCPREQUEST of 192.168.1.146 on eth0.2 to 255.255.255.255 port 67 (xid=0x21e3114e) DHCPOFFER of 192.168.1.146 from 192.168.1.254 DHCPACK of 192.168.1.146 from 192.168.1.254 bound to 192.168.1.146 -- renewal in 1366 seconds. root@ubuntu:~# dhclient -v eth0.3 Internet Systems Consortium DHCP Client 4.2.4 Copyright 2004-2012 Internet Systems Consortium. All rights reserved. For info, please visit https://www.isc.org/software/dhcp/ Listening on LPF/eth0.3/00:00:00:00:00:33 Sending on LPF/eth0.3/00:00:00:00:00:33 Sending on Socket/fallback DHCPDISCOVER on eth0.3 to 255.255.255.255 port 67 interval 3 (xid=0x11dc5f03) DHCPREQUEST of 192.168.1.147 on eth0.3 to 255.255.255.255 port 67 (xid=0x11dc5f03) DHCPOFFER of 192.168.1.147 from 192.168.1.254 DHCPACK of 192.168.1.147 from 192.168.1.254 bound to 192.168.1.147 -- renewal in 1657 seconds. root@ubuntu:~# ip -4 link sh 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000 link/ether 00:0c:29:bc:fc:8b brd ff:ff:ff:ff:ff:ff 18: eth0.1@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT group default link/ether 00:00:00:00:00:11 brd ff:ff:ff:ff:ff:ff 19: eth0.2@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT group default link/ether 00:00:00:00:00:22 brd ff:ff:ff:ff:ff:ff 20: eth0.3@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT group default link/ether 00:00:00:00:00:33 brd ff:ff:ff:ff:ff:ff root@ubuntu:~# ip -4 addr sh 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 18: eth0.1@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default inet 192.168.1.145/24 brd 192.168.1.255 scope global eth0.1 valid_lft forever preferred_lft forever 19: eth0.2@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default inet 192.168.1.146/24 brd 192.168.1.255 scope global eth0.2 valid_lft forever preferred_lft forever 20: eth0.3@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default inet 192.168.1.147/24 brd 192.168.1.255 scope global eth0.3 valid_lft forever preferred_lft forever root@ubuntu:~# ip -4 route sh default via 192.168.1.254 dev eth0.1 192.168.1.0/24 dev eth0.1 proto kernel scope link src 192.168.1.145 192.168.1.0/24 dev eth0.2 proto kernel scope link src 192.168.1.146 192.168.1.0/24 dev eth0.3 proto kernel scope link src 192.168.1.147 root@ubuntu:~# arping -c 5 -I eth0.1 192.168.1.254 ARPING 192.168.1.254 from 192.168.1.145 eth0.1 Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 6.936ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 2.986ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 0.654ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 5.137ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 2.426ms Sent 5 probes (1 broadcast(s)) Received 5 response(s) root@ubuntu:~# arping -c 5 -I eth0.2 192.168.1.254 ARPING 192.168.1.254 from 192.168.1.146 eth0.2 Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 5.665ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 3.753ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 16.500ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 3.287ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 32.438ms Sent 5 probes (1 broadcast(s)) Received 5 response(s) root@ubuntu:~# arping -c 5 -I eth0.3 192.168.1.254 ARPING 192.168.1.254 from 192.168.1.147 eth0.3 Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 4.422ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 2.429ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 2.321ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 40.423ms Unicast reply from 192.168.1.254 [58:98:35:57:a0:70] 2.268ms Sent 5 probes (1 broadcast(s)) Received 5 response(s) root@ubuntu:~# tcpdump -n -i eth0.1 -v & [1] 5317 root@ubuntu:~# ping -c5 -q -I eth0.1 192.168.1.254 PING 192.168.1.254 (192.168.1.254) from 192.168.1.145 eth0.1: 56(84) bytes of data. tcpdump: listening on eth0.1, link-type EN10MB (Ethernet), capture size 65535 bytes 13:18:37.612558 IP (tos 0x0, ttl 64, id 2595, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.145 > 192.168.1.254: ICMP echo request, id 5318, seq 2, length 64 13:18:37.618864 IP (tos 0x68, ttl 64, id 14493, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.145: ICMP echo reply, id 5318, seq 2, length 64 13:18:37.743650 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.1.87 tell 192.168.1.86, length 46 13:18:38.134997 IP (tos 0x0, ttl 128, id 23547, offset 0, flags [none], proto UDP (17), length 229) 192.168.1.86.138 > 192.168.1.255.138: NBT UDP PACKET(138) 13:18:38.614580 IP (tos 0x0, ttl 64, id 2596, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.145 > 192.168.1.254: ICMP echo request, id 5318, seq 3, length 64 13:18:38.793479 IP (tos 0x68, ttl 64, id 14495, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.145: ICMP echo reply, id 5318, seq 3, length 64 13:18:39.151282 IP6 (class 0x68, hlim 255, next-header ICMPv6 (58) payload length: 32) fe80::5a98:35ff:fe57:e070 > ff02::1:ff6b:e9b4: [icmp6 sum ok] ICMP6, neighbor solicitation, length 32, who has 2001:818:d812:da00:8ae3:abff:fe6b:e9b4 source link-address option (1), length 8 (1): 58:98:35:57:a0:70 13:18:39.615612 IP (tos 0x0, ttl 64, id 2597, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.145 > 192.168.1.254: ICMP echo request, id 5318, seq 4, length 64 13:18:39.746981 IP (tos 0x68, ttl 64, id 14496, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.145: ICMP echo reply, id 5318, seq 4, length 64 --- 192.168.1.254 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4008ms rtt min/avg/max/mdev = 2.793/67.810/178.934/73.108 ms root@ubuntu:~# killall tcpdump >> /dev/null 2>&1 9 packets captured 12 packets received by filter 0 packets dropped by kernel [1]+ Done tcpdump -n -i eth0.1 -v root@ubuntu:~# tcpdump -n -i eth0.2 -v & [1] 5320 root@ubuntu:~# ping -c5 -q -I eth0.2 192.168.1.254 PING 192.168.1.254 (192.168.1.254) from 192.168.1.146 eth0.2: 56(84) bytes of data. tcpdump: listening on eth0.2, link-type EN10MB (Ethernet), capture size 65535 bytes 13:18:41.536874 ARP, Ethernet (len 6), IPv4 (len 4), Reply 192.168.1.254 is-at 58:98:35:57:a0:70, length 46 13:18:41.536933 IP (tos 0x0, ttl 64, id 2599, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.146 > 192.168.1.254: ICMP echo request, id 5321, seq 1, length 64 13:18:41.539255 IP (tos 0x68, ttl 64, id 14507, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.146: ICMP echo reply, id 5321, seq 1, length 64 13:18:42.127715 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.1.87 tell 192.168.1.86, length 46 13:18:42.511725 IP (tos 0x0, ttl 64, id 2600, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.146 > 192.168.1.254: ICMP echo request, id 5321, seq 2, length 64 13:18:42.514385 IP (tos 0x68, ttl 64, id 14527, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.146: ICMP echo reply, id 5321, seq 2, length 64 13:18:42.743856 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.1.87 tell 192.168.1.86, length 46 13:18:43.511727 IP (tos 0x0, ttl 64, id 2601, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.146 > 192.168.1.254: ICMP echo request, id 5321, seq 3, length 64 13:18:43.513768 IP (tos 0x68, ttl 64, id 14528, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.146: ICMP echo reply, id 5321, seq 3, length 64 13:18:43.637598 IP (tos 0x0, ttl 128, id 23551, offset 0, flags [none], proto UDP (17), length 225) 192.168.1.86.17500 > 255.255.255.255.17500: UDP, length 197 13:18:43.641185 IP (tos 0x0, ttl 128, id 23552, offset 0, flags [none], proto UDP (17), length 225) 192.168.1.86.17500 > 192.168.1.255.17500: UDP, length 197 13:18:43.641201 IP (tos 0x0, ttl 128, id 23553, offset 0, flags [none], proto UDP (17), length 225) 192.168.1.86.17500 > 255.255.255.255.17500: UDP, length 197 13:18:43.743890 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.1.87 tell 192.168.1.86, length 46 13:18:44.510758 IP (tos 0x0, ttl 64, id 2602, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.146 > 192.168.1.254: ICMP echo request, id 5321, seq 4, length 64 13:18:44.512892 IP (tos 0x68, ttl 64, id 14538, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.146: ICMP echo reply, id 5321, seq 4, length 64 13:18:45.510794 IP (tos 0x0, ttl 64, id 2603, offset 0, flags [DF], proto ICMP (1), length 84) 192.168.1.146 > 192.168.1.254: ICMP echo request, id 5321, seq 5, length 64 13:18:45.519701 IP (tos 0x68, ttl 64, id 14539, offset 0, flags [none], proto ICMP (1), length 84) 192.168.1.254 > 192.168.1.146: ICMP echo reply, id 5321, seq 5, length 64 13:18:49.287554 IP6 (class 0x68, hlim 255, next-header ICMPv6 (58) payload length: 32) fe80::5a98:35ff:fe57:e070 > ff02::1:ff6b:e9b4: [icmp6 sum ok] ICMP6, neighbor solicitation, length 32, who has 2001:818:d812:da00:8ae3:abff:fe6b:e9b4 source link-address option (1), length 8 (1): 58:98:35:57:a0:70 13:18:50.013463 IP (tos 0x0, ttl 255, id 50737, offset 0, flags [DF], proto UDP (17), length 73) 192.168.1.146.5353 > 224.0.0.251.5353: 0 [2q] PTR (QM)? _ipps._tcp.local. PTR (QM)? _ipp._tcp.local. (45) 13:18:50.218874 IP6 (class 0x68, hlim 255, next-header ICMPv6 (58) payload length: 32) fe80::5a98:35ff:fe57:e070 > ff02::1:ff6b:e9b4: [icmp6 sum ok] ICMP6, neighbor solicitation, length 32, who has 2001:818:d812:da00:8ae3:abff:fe6b:e9b4 source link-address option (1), length 8 (1): 58:98:35:57:a0:70 13:18:51.129961 IP6 (class 0x68, hlim 255, next-header ICMPv6 (58) payload length: 32) fe80::5a98:35ff:fe57:e070 > ff02::1:ff6b:e9b4: [icmp6 sum ok] ICMP6, neighbor solicitation, length 32, who has 2001:818:d812:da00:8ae3:abff:fe6b:e9b4 source link-address option (1), length 8 (1): 58:98:35:57:a0:70 13:18:52.197074 IP6 (hlim 255, next-header UDP (17) payload length: 53) 2001:818:d812:da00:200:ff:fe00:22.5353 > ff02::fb.5353: [udp sum ok] 0 [2q] PTR (QM)? _ipps._tcp.local. PTR (QM)? _ipp._tcp.local. (45) 13:18:54.128240 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.1.87 tell 192.168.1.86, length 46 --- 192.168.1.254 ping statistics --- 5 packets transmitted, 0 received, 100% packet loss, time 4000ms root@ubuntu:~# killall tcpdump >> /dev/null 2>&1 13:18:54.657731 IP6 (class 0x68, hlim 255, next-header ICMPv6 (58) payload length: 32) fe80::5a98:35ff:fe57:e070 > ff02::1:ff6b:e9b4: [icmp6 sum ok] ICMP6, neighbor solicitation, length 32, who has 2001:818:d812:da00:8ae3:abff:fe6b:e9b4 source link-address option (1), length 8 (1): 58:98:35:57:a0:70 13:18:54.743174 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has 192.168.1.87 tell 192.168.1.86, length 46 25 packets captured 26 packets received by filter 0 packets dropped by kernel [1]+ Done tcpdump -n -i eth0.2 -v root@ubuntu:~# tcpdump -n -i eth0.3 icmp & [1] 5324 root@ubuntu:~# ping -c5 -q -I eth0.3 192.168.1.254 PING 192.168.1.254 (192.168.1.254) from 192.168.1.147 eth0.3: 56(84) bytes of data. tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth0.3, link-type EN10MB (Ethernet), capture size 65535 bytes 13:18:56.373434 IP 192.168.1.147 > 192.168.1.254: ICMP echo request, id 5325, seq 1, length 64 13:18:57.372116 IP 192.168.1.147 > 192.168.1.254: ICMP echo request, id 5325, seq 2, length 64 13:18:57.381263 IP 192.168.1.254 > 192.168.1.147: ICMP echo reply, id 5325, seq 2, length 64 13:18:58.371141 IP 192.168.1.147 > 192.168.1.254: ICMP echo request, id 5325, seq 3, length 64 13:18:58.373275 IP 192.168.1.254 > 192.168.1.147: ICMP echo reply, id 5325, seq 3, length 64 13:18:59.371165 IP 192.168.1.147 > 192.168.1.254: ICMP echo request, id 5325, seq 4, length 64 13:18:59.373259 IP 192.168.1.254 > 192.168.1.147: ICMP echo reply, id 5325, seq 4, length 64 13:19:00.371211 IP 192.168.1.147 > 192.168.1.254: ICMP echo request, id 5325, seq 5, length 64 13:19:00.373278 IP 192.168.1.254 > 192.168.1.147: ICMP echo reply, id 5325, seq 5, length 64 --- 192.168.1.254 ping statistics --- 5 packets transmitted, 1 received, 80% packet loss, time 4001ms rtt min/avg/max/mdev = 13.666/13.666/13.666/0.000 ms root@ubuntu:~# killall tcpdump >> /dev/null 2>&1 9 packets captured 10 packets received by filter 0 packets dropped by kernel [1]+ Done tcpdump -n -i eth0.3 icmp root@ubuntu:~# arp -n Address HWtype HWaddress Flags Mask Iface 192.168.1.254 ether 58:98:35:57:a0:70 C eth0.1 192.168.1.254 ether 58:98:35:57:a0:70 C eth0.2 192.168.1.254 ether 58:98:35:57:a0:70 C eth0.3

    Read the article

  • How is the MTU is 65535 in UDP but ethernet does not allow frame size more than 1500 bytes

    - by nikku
    I am using a fast ethernet of 100 Mbps, whose frame size is less than 1500 bytes (1472 bytes for payload as per my textbook). In that, I was able to send and receive a UDP packet of message size 65507 bytes, which means the packet size was 65507 + 20 (IP Header) + 8 (UDP Header) = 65535. If the frame's payload size itself is maximum of 1472 bytes (as per my textbook), how can the packet size of IP be greater than that which here is 65535? I used sender code as char buffer[100000]; for (int i = 1; i < 100000; i++) { int len = send (socket_id, buffer, i); printf("%d\n", len); } Receiver code as while (len = recv (socket_id, buffer, 100000)) { printf("%d\n". len); } I observed that send returns -1 on i > 65507 and recv prints or receives a packet of maximum of length 65507.

    Read the article

  • benchmark tcp: ab or iperf like tool to send hex/binary/pcap data?

    - by olan
    Hello all, I have written a server in Twisted for a current project I'm working on, and now I need to test it. It receives TCP packets, with the payload consisting of just a serialised binary string. I want to be able to test the server for concurrency/throughput using the binary data as the payload, but can not find any tool that will allow me to do this. I tried iperf -F but it didn't work, as I think it was sending the binary/hex data as chars. I've also looked at ab which seems to be perfect - if only for http. As well as these, I've had a look at tcpreplay, but it doesn't perform any testing (or establish TCP connections) so it's not much use. Any help would be greatly appreciated as I'm rather stuck on this one!

    Read the article

  • How is the MTU is 65535 in UDP but ethernet does not allow frame size more than 1500 bytes

    - by nikku
    I am using a fast ethernet of 100 Mbps, whose frame size is less than 1500 bytes (1472 bytes for payload as per my textbook). In that, I was able to send and receive a UDP packet of message size 65507 bytes, which means the packet size was 65507 + 20 (IP Header) + 8 (UDP Header) = 65535. If the frame's payload size itself is maximum of 1472 bytes (as per my textbook), how can the packet size of IP be greater than that which here is 65535? I used sender code as char buffer[100000]; for (int i = 1; i < 100000; i++) { int len = send (socket_id, buffer, i); printf("%d\n", len); } Receiver code as while (len = recv (socket_id, buffer, 100000)) { printf("%d\n". len); } I observed that send returns -1 on i > 65507 and recv prints or receives a packet of maximum of length 65507.

    Read the article

  • Host data transfer limit calculations and network protocol headers

    - by UpTheCreek
    OK, this might be a really stupid question, but... I'm building a web app that utilises websockets. There's fairly rapid messaging going on, so I've been taking a look at the network traffic with wireshark, to see if there's any way of reducing the amount of data we are sending over the wire, and hence costs. A typical message has approx 150 byte data payload, and according to wireshark the lower layer stuff takes up about: Ethernet: 14 bytes IP: 20 Bytes TCP: 20 Bytes My question is, are these network headers included in data transfer calculations? What about TCP ACK messages? (another 54 bytes according to wireshark) This may seem petty, but because we have so much messaging going on, and because the payload is a similar size to these headers, it's significant.

    Read the article

  • Converting AES encryption token code in C# to php

    - by joey
    Hello, I have the following .Net code which takes two inputs. 1) A 128 bit base 64 encoded key and 2) the userid. It outputs the AES encrypted token. I need the php equivalent of the same code, but dont know which corresponding php classes are to be used for RNGCryptoServiceProvider,RijndaelManaged,ICryptoTransform,MemoryStream and CryptoStream. Im stuck so any help regarding this would be really appreciated. using System; using System.Text; using System.IO; using System.Security.Cryptography; class AESToken { [STAThread] static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: AESToken key userId\n"); Console.WriteLine("key Specifies 128-bit AES key base64 encoded supplied by MediaNet to the partner"); Console.WriteLine("userId specifies the unique id"); return -1; } string key = args[0]; string userId = args[1]; StringBuilder sb = new StringBuilder(); // This example code uses the magic string “CAMB2B”. The implementer // must use the appropriate magic string for the web services API. sb.Append("CAMB2B"); sb.Append(args[1]); // userId sb.Append('|'); // pipe char sb.Append(System.DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ssUTC")); //timestamp Byte[] payload = Encoding.ASCII.GetBytes(sb.ToString()); byte[] salt = new Byte[16]; // 16 bytes of random salt RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(salt); // the plaintext is 16 bytes of salt followed by the payload. byte[] plaintext = new byte[salt.Length + payload.Length]; salt.CopyTo(plaintext, 0); payload.CopyTo(plaintext, salt.Length); // the AES cryptor: 128-bit key, 128-bit block size, CBC mode RijndaelManaged cryptor = new RijndaelManaged(); cryptor.KeySize = 128; cryptor.BlockSize = 128; cryptor.Mode = CipherMode.CBC; cryptor.GenerateIV(); cryptor.Key = Convert.FromBase64String(args[0]); // the key byte[] iv = cryptor.IV; // the IV. // do the encryption ICryptoTransform encryptor = cryptor.CreateEncryptor(cryptor.Key, iv); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(plaintext, 0, plaintext.Length); cs.FlushFinalBlock(); byte[] ciphertext = ms.ToArray(); ms.Close(); cs.Close(); // build the token byte[] tokenBytes = new byte[iv.Length + ciphertext.Length]; iv.CopyTo(tokenBytes, 0); ciphertext.CopyTo(tokenBytes, iv.Length); string token = Convert.ToBase64String(tokenBytes); Console.WriteLine(token); return 0; } } Please help. Thank You.

    Read the article

  • Solved: Operation is not valid due to the current state of the object

    - by ChrisD
    We use public static methods decorated with [WebMethod] to support our Ajax Postbacks.   Recently, I received an error from a UI developing stating he was receiving the following error when attempting his post back: {   "Message": "Operation is not valid due to the current state of the object.",   "StackTrace": "   at System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary`2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",   "ExceptionType": "System.InvalidOperationException" }   Goggling this error brought me little support.  All the results talked about increasing the aspnet:MaxJsonDeserializerMembers value to handle larger payloads.  Since 1) I’m not using the asp.net ajax model and 2) the payload is very small, this clearly was not the cause of my issue. Here’s the payload the UI developer was sending to the endpoint: {   "FundingSource": {     "__type": "XX.YY.Engine.Contract.Funding.EvidenceBasedFundingSource,  XX.YY.Engine.Contract",     "MeansType": 13,     "FundingMethodName": "LegalTender",   },   "AddToProfile": false,   "ProfileNickName": "",   "FundingAmount": 0 } By tweaking the JSON I’ve found the culprit. Apparently the default JSS Serializer used doesn’t like the assembly name in the __type value.  Removing the assembly portion of the type name resolved my issue. { "FundingSource": { "__type": "XX.YY.Engine.Contract.Funding.EvidenceBasedFundingSource", "MeansType": 13, "FundingMethodName": "LegalTender", }, "AddToProfile": false, "ProfileNickName": "", "FundingAmount": 0 }

    Read the article

  • Building applications with WPF, MVVM and Prism(aka CAG)

    - by skjagini
    In this article I am going to walk through an application using WPF and Prism (aka composite application guidance, CAG) which simulates engaging a taxi (cab).  The rules are simple, the app would have3 screens A login screen to authenticate the user An information screen. A screen to engage the cab and roam around and calculating the total fare Metered Rate of Fare The meter is required to be engaged when a cab is occupied by anyone $3.00 upon entry $0.35 for each additional unit The unit fare is: one-fifth of a mile, when the cab is traveling at 6 miles an hour or more; or 60 seconds when not in motion or traveling at less than 12 miles per hour. Night surcharge of $.50 after 8:00 PM & before 6:00 AM Peak hour Weekday Surcharge of $1.00 Monday - Friday after 4:00 PM & before 8:00 PM New York State Tax Surcharge of $.50 per ride. Example: Friday (2010-10-08) 5:30pm Start at Lexington Ave & E 57th St End at Irving Pl & E 15th St Start = $3.00 Travels 2 miles at less than 6 mph for 15 minutes = $3.50 Travels at more than 12 mph for 5 minutes = $1.75 Peak hour Weekday Surcharge = $1.00 (ride started at 5:30 pm) New York State Tax Surcharge = $0.50 Before we dive into the app, I would like to give brief description about the framework.  If you want to jump on to the source code, scroll all the way to the end of the post. MVVM MVVM pattern is in no way related to the usage of PRISM in your application and should be considered if you are using WPF irrespective of PRISM or not. Lets say you are not familiar with MVVM, your typical UI would involve adding some UI controls like text boxes, a button, double clicking on the button,  generating event handler, calling a method from business layer and updating the user interface, it works most of the time for developing small scale applications. The problem with this approach is that there is some amount of code specific to business logic wrapped in UI specific code which is hard to unit test it, mock it and MVVM helps to solve the exact problem. MVVM stands for Model(M) – View(V) – ViewModel(VM),  based on the interactions with in the three parties it should be called VVMM,  MVVM sounds more like MVC (Model-View-Controller) so the name. Why it should be called VVMM: View – View Model - Model WPF allows to create user interfaces using XAML and MVVM takes it to the next level by allowing complete separation of user interface and business logic. In WPF each view will have a property, DataContext when set to an instance of a class (which happens to be your view model) provides the data the view is interested in, i.e., view interacts with view model and at the same time view model interacts with view through DataContext. Sujith, if view and view model are interacting directly with each other how does MVVM is helping me separation of concerns? Well, the catch is DataContext is of type Object, since it is of type object view doesn’t know exact type of view model allowing views and views models to be loosely coupled. View models aggregate data from models (data access layer, services, etc) and make it available for views through properties, methods etc, i.e., View Models interact with Models. PRISM Prism is provided by Microsoft Patterns and Practices team and it can be downloaded from codeplex for source code,  samples and documentation on msdn.  The name composite implies, to compose user interface from different modules (views) without direct dependencies on each other, again allowing  loosely coupled development. Well Sujith, I can already do that with user controls, why shall I learn another framework?  That’s correct, you can decouple using user controls, but you still have to manage some amount of coupling, like how to do you communicate between the controls, how do you subscribe/unsubscribe, loading/unloading views dynamically. Prism is not a replacement for user controls, provides the following features which greatly help in designing the composite applications. Dependency Injection (DI)/ Inversion of Control (IoC) Modules Regions Event Aggregator  Commands Simply put, MVVM helps building a single view and Prism helps building an application using the views There are other open source alternatives to Prism, like MVVMLight, Cinch, take a look at them as well. Lets dig into the source code.  1. Solution The solution is made of the following projects Framework: Holds the common functionality in building applications using WPF and Prism TaxiClient: Start up project, boot strapping and app styling TaxiCommon: Helps with the business logic TaxiModules: Holds the meat of the application with views and view models TaxiTests: To test the application 2. DI / IoC Dependency Injection (DI) as the name implies refers to injecting dependencies and Inversion of Control (IoC) means the calling code has no direct control on the dependencies, opposite of normal way of programming where dependencies are passed by caller, i.e inversion; aside from some differences in terminology the concept is same in both the cases. The idea behind DI/IoC pattern is to reduce the amount of direct coupling between different components of the application, the higher the dependency the more tightly coupled the application resulting in code which is hard to modify, unit test and mock.  Initializing Dependency Injection through BootStrapper TaxiClient is the starting project of the solution and App (App.xaml)  is the starting class that gets called when you run the application. From the App’s OnStartup method we will invoke BootStrapper.   namespace TaxiClient { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e);   (new BootStrapper()).Run(); } } } BootStrapper is your contact point for initializing the application including dependency injection, creating Shell and other frameworks. We are going to use Unity for DI and there are lot of open source DI frameworks like Spring.Net, StructureMap etc with different feature set  and you can choose a framework based on your preferences. Note that Prism comes with in built support for Unity, for example we are deriving from UnityBootStrapper in our case and for any other DI framework you have to extend the Prism appropriately   namespace TaxiClient { public class BootStrapper: UnityBootstrapper { protected override IModuleCatalog CreateModuleCatalog() { return new ConfigurationModuleCatalog(); } protected override DependencyObject CreateShell() { Framework.FrameworkBootStrapper.Run(Container, Application.Current.Dispatcher);   Shell shell = new Shell(); shell.ResizeMode = ResizeMode.NoResize; shell.Show();   return shell; } } } Lets take a look into  FrameworkBootStrapper to check out how to register with unity container. namespace Framework { public class FrameworkBootStrapper { public static void Run(IUnityContainer container, Dispatcher dispatcher) { UIDispatcher uiDispatcher = new UIDispatcher(dispatcher); container.RegisterInstance<IDispatcherService>(uiDispatcher);   container.RegisterType<IInjectSingleViewService, InjectSingleViewService>( new ContainerControlledLifetimeManager());   . . . } } } In the above code we are registering two components with unity container. You shall observe that we are following two different approaches, RegisterInstance and RegisterType.  With RegisterInstance we are registering an existing instance and the same instance will be returned for every request made for IDispatcherService   and with RegisterType we are requesting unity container to create an instance for us when required, i.e., when I request for an instance for IInjectSingleViewService, unity will create/return an instance of InjectSingleViewService class and with RegisterType we can configure the life time of the instance being created. With ContaienrControllerLifetimeManager, the unity container caches the instance and reuses for any subsequent requests, without recreating a new instance. Lets take a look into FareViewModel.cs and it’s constructor. The constructor takes one parameter IEventAggregator and if you try to find all references in your solution for IEventAggregator, you will not find a single location where an instance of EventAggregator is passed directly to the constructor. The compiler still finds an instance and works fine because Prism is already configured when used with Unity container to return an instance of EventAggregator when requested for IEventAggregator and in this particular case it is called constructor injection. public class FareViewModel:ObservableBase, IDataErrorInfo { ... private IEventAggregator _eventAggregator;   public FareViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; InitializePropertyNames(); InitializeModel(); PropertyChanged += OnPropertyChanged; } ... 3. Shell Shells are very similar in operation to Master Pages in asp.net or MDI in Windows Forms. And shells contain regions which display the views, you can have as many regions as you wish in a given view. You can also nest regions. i.e, one region can load a view which in itself may contain other regions. We have to create a shell at the start of the application and are doing it by overriding CreateShell method from BootStrapper From the following Shell.xaml you shall notice that we have two content controls with Region names as ‘MenuRegion’ and ‘MainRegion’.  The idea here is that you can inject any user controls into the regions dynamically, i.e., a Menu User Control for MenuRegion and based on the user action you can load appropriate view into MainRegion.    <Window x:Class="TaxiClient.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism" Title="Taxi" Height="370" Width="800"> <Grid Margin="2"> <ContentControl Regions:RegionManager.RegionName="MenuRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />   <ContentControl Grid.Row="1" Regions:RegionManager.RegionName="MainRegion" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" /> <!--<Border Grid.ColumnSpan="2" BorderThickness="2" CornerRadius="3" BorderBrush="LightBlue" />-->   </Grid> </Window> 4. Modules Prism provides the ability to build composite applications and modules play an important role in it. For example if you are building a Mortgage Loan Processor application with 3 components, i.e. customer’s credit history,  existing mortgages, new home/loan information; and consider that the customer’s credit history component involves gathering data about his/her address, background information, job details etc. The idea here using Prism modules is to separate the implementation of these 3 components into their own visual studio projects allowing to build components with no dependency on each other and independently. If we need to add another component to the application, the component can be developed by in house team or some other team in the organization by starting with a new Visual Studio project and adding to the solution at the run time with very little knowledge about the application. Prism modules are defined by implementing the IModule interface and each visual studio project to be considered as a module should implement the IModule interface.  From the BootStrapper.cs you shall observe that we are overriding the method by returning a ConfiguratingModuleCatalog which returns the modules that are registered for the application using the app.config file  and you can also add module using code. Lets take a look into configuration file.   <?xml version="1.0"?> <configuration> <configSections> <section name="modules" type="Microsoft.Practices.Prism.Modularity.ModulesConfigurationSection, Microsoft.Practices.Prism"/> </configSections> <modules> <module assemblyFile="TaxiModules.dll" moduleType="TaxiModules.ModuleInitializer, TaxiModules" moduleName="TaxiModules"/> </modules> </configuration> Here we are adding TaxiModules project to our solution and TaxiModules.ModuleInitializer implements IModule interface   5. Module Mapper With Prism modules you can dynamically add or remove modules from the regions, apart from that Prism also provides API to control adding/removing the views from a region within the same module. Taxi Information Screen: Engage the Taxi Screen: The sample application has two screens, ‘Taxi Information’ and ‘Engage the Taxi’ and they both reside in same module, TaxiModules. ‘Engage the Taxi’ is again made of two user controls, FareView on the left and TotalView on the right. We have created a Shell with two regions, MenuRegion and MainRegion with menu loaded into MenuRegion. We can create a wrapper user control called EngageTheTaxi made of FareView and TotalView and load either TaxiInfo or EngageTheTaxi into MainRegion based on the user action. Though it will work it tightly binds the user controls and for every combination of user controls, we need to create a dummy wrapper control to contain them. Instead we can apply the principles we learned so far from Shell/regions and introduce another template (LeftAndRightRegionView.xaml) made of two regions Region1 (left) and Region2 (right) and load  FareView and TotalView dynamically.  To help with loading of the views dynamically I have introduce an helper an interface, IInjectSingleViewService,  idea suggested by Mike Taulty, a must read blog for .Net developers. using System; using System.Collections.Generic; using System.ComponentModel;   namespace Framework.PresentationUtility.Navigation {   public interface IInjectSingleViewService : INotifyPropertyChanged { IEnumerable<CommandViewDefinition> Commands { get; } IEnumerable<ModuleViewDefinition> Modules { get; }   void RegisterViewForRegion(string commandName, string viewName, string regionName, Type viewType); void ClearViewFromRegion(string viewName, string regionName); void RegisterModule(string moduleName, IList<ModuleMapper> moduleMappers); } } The Interface declares three methods to work with views: RegisterViewForRegion: Registers a view with a particular region. You can register multiple views and their regions under one command.  When this particular command is invoked all the views registered under it will be loaded into their regions. ClearViewFromRegion: To unload a specific view from a region. RegisterModule: The idea is when a command is invoked you can load the UI with set of controls in their default position and based on the user interaction, you can load different contols in to different regions on the fly.  And it is supported ModuleViewDefinition and ModuleMappers as shown below. namespace Framework.PresentationUtility.Navigation { public class ModuleViewDefinition { public string ModuleName { get; set; } public IList<ModuleMapper> ModuleMappers; public ICommand Command { get; set; } }   public class ModuleMapper { public string ViewName { get; set; } public string RegionName { get; set; } public Type ViewType { get; set; } } } 6. Event Aggregator Prism event aggregator enables messaging between components as in Observable pattern, Notifier notifies the Observer which receives notification it is interested in. When it comes to Observable pattern, Observer has to unsubscribes for notifications when it no longer interested in notifications, which allows the Notifier to remove the Observer’s reference from it’s local cache. Though .Net has managed garbage collection it cannot remove inactive the instances referenced by an active instance resulting in memory leak, keeping the Observers in memory as long as Notifier stays in memory.  Developers have to be very careful to unsubscribe when necessary and it often gets overlooked, to overcome these problems Prism Event Aggregator uses weak references to cache the reference (Observer in this case)  and releases the reference (memory) once the instance goes out of scope. Using event aggregator is very simple, declare a generic type of CompositePresenationEvent by inheriting from it. using Microsoft.Practices.Prism.Events; using TaxiCommon.BAO;   namespace TaxiCommon.CompositeEvents { public class TaxiOnMoveEvent:CompositePresentationEvent<TaxiOnMove> { } }   TaxiOnMove.cs includes the properties which we want to exchange between the parties, FareView and TotalView. using System;   namespace TaxiCommon.BAO { public class TaxiOnMove { public TimeSpan MinutesAtTweleveMPH { get; set; } public double MilesAtSixMPH { get; set; } } }   Lets take a look into FareViewodel (Notifier) and how it raises the event.  Here we are raising the event by getting the event through GetEvent<..>() and publishing it with the payload private void OnAddMinutes(object obj) { TaxiOnMove payload = new TaxiOnMove(); if(MilesAtSixMPH != null) payload.MilesAtSixMPH = MilesAtSixMPH.Value; if(MinutesAtTweleveMPH != null) payload.MinutesAtTweleveMPH = new TimeSpan(0,0,MinutesAtTweleveMPH.Value,0);   _eventAggregator.GetEvent<TaxiOnMoveEvent>().Publish(payload); ResetMinutesAndMiles(); } And TotalViewModel(Observer) subscribes to notifications by getting the event through GetEvent<..>() namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { .... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator; ... }   private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>() .Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>() .Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>() .Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   ... private void OnTaxiMove(TaxiOnMove taxiOnMove) { OnMoveFare fare = new OnMoveFare(taxiOnMove); Fares.Add(fare); SetTotalFare(new []{fare}); }   .... 7. MVVM through example In this section we are going to look into MVVM implementation through example.  I have all the modules declared in a single project, TaxiModules, again it is not necessary to have them into one project. Once the user logs into the application, will be greeted with the ‘Engage the Taxi’ screen which is made of two user controls, FareView.xaml and TotalView.Xaml. As you can see from the solution explorer, each of them have their own code behind files and  ViewModel classes, FareViewMode.cs, TotalViewModel.cs Lets take a look in to the FareView and how it interacts with FareViewModel using MVVM implementation. FareView.xaml acts as a view and FareViewMode.cs is it’s view model. The FareView code behind class   namespace TaxiModules.Views { /// <summary> /// Interaction logic for FareView.xaml /// </summary> public partial class FareView : UserControl { public FareView(FareViewModel viewModel) { InitializeComponent(); this.Loaded += (s, e) => { this.DataContext = viewModel; }; } } } The FareView is bound to FareViewModel through the data context  and you shall observe that DataContext is of type Object, i.e. the FareView doesn’t really know the type of ViewModel (FareViewModel). This helps separation of View and ViewModel as View and ViewModel are independent of each other, you can bind FareView to FareViewModel2 as well and the application compiles just fine. Lets take a look into FareView xaml file  <UserControl x:Class="TaxiModules.Views.FareView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" xmlns:Commands="clr-namespace:Microsoft.Practices.Prism.Commands;assembly=Microsoft.Practices.Prism"> <Grid Margin="10" > ....   <Border Style="{DynamicResource innerBorder}" Grid.Row="0" Grid.Column="0" Grid.RowSpan="11" Grid.ColumnSpan="2" Panel.ZIndex="1"/>   <Label Grid.Row="0" Content="Engage the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="1" Content="Select the State"/> <ComboBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding States}" Height="auto"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"/> </DataTemplate> </ComboBox.ItemTemplate> <ComboBox.SelectedItem> <Binding Path="SelectedState" Mode="TwoWay"/> </ComboBox.SelectedItem> </ComboBox> <Label Grid.Row="2" Content="Select the Date of Entry"/> <Toolkit:DatePicker Grid.Row="2" Grid.Column="1" SelectedDate="{Binding DateOfEntry, ValidatesOnDataErrors=true}" /> <Label Grid.Row="3" Content="Enter time 24hr format"/> <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding TimeOfEntry, TargetNullValue=''}"/> <Button Grid.Row="4" Grid.Column="1" Content="Start the Meter" Commands:Click.Command="{Binding StartMeterCommand}" />   <Label Grid.Row="5" Content="Run the Taxi" Style="{DynamicResource innerHeader}"/> <Label Grid.Row="6" Content="Number of Miles &lt;@6mph"/> <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding MilesAtSixMPH, TargetNullValue='', ValidatesOnDataErrors=true}"/> <Label Grid.Row="7" Content="Number of Minutes @12mph"/> <TextBox Grid.Row="7" Grid.Column="1" Text="{Binding MinutesAtTweleveMPH, TargetNullValue=''}"/> <Button Grid.Row="8" Grid.Column="1" Content="Add Minutes and Miles " Commands:Click.Command="{Binding AddMinutesCommand}"/> <Label Grid.Row="9" Content="Other Operations" Style="{DynamicResource innerHeader}"/> <Button Grid.Row="10" Grid.Column="1" Content="Reset the Meter" Commands:Click.Command="{Binding ResetCommand}"/>   </Grid> </UserControl> The highlighted code from the above code shows data binding, for example ComboBox which displays list of states has it’s ItemsSource bound to States property, with DataTemplate bound to Name and SelectedItem  to SelectedState. You might be wondering what are all these properties and how it is able to bind to them.  The answer lies in data context, i.e., when you bound a control, WPF looks for data context on the root object (Grid in this case) and if it can’t find data context it will look into root’s root, i.e. FareView UserControl and it is bound to FareViewModel.  Each of those properties have be declared on the ViewModel for the View to bind correctly. To put simply, View is bound to ViewModel through data context of type object and every control that is bound on the View actually binds to the public property on the ViewModel. Lets look into the ViewModel code (the following code is not an exact copy of FareViewMode.cs, pasted relevant code for this section)   namespace TaxiModules.ViewModels { public class FareViewModel:ObservableBase, IDataErrorInfo { public List<USState> States { get { return USStates.StateList; } }   public USState SelectedState { get { return _selectedState; } set { _selectedState = value; RaisePropertyChanged(_selectedStatePropertyName); } }   public DateTime? DateOfEntry { get { return _dateOfEntry; } set { _dateOfEntry = value; RaisePropertyChanged(_dateOfEntryPropertyName); } }   public TimeSpan? TimeOfEntry { get { return _timeOfEntry; } set { _timeOfEntry = value; RaisePropertyChanged(_timeOfEntryPropertyName); } }   public double? MilesAtSixMPH { get { return _milesAtSixMPH; } set { _milesAtSixMPH = value; RaisePropertyChanged(_distanceAtSixMPHPropertyName); } }   public int? MinutesAtTweleveMPH { get { return _minutesAtTweleveMPH; } set { _minutesAtTweleveMPH = value; RaisePropertyChanged(_minutesAtTweleveMPHPropertyName); } }   public ICommand StartMeterCommand { get { if(_startMeterCommand == null) { _startMeterCommand = new DelegateCommand<object>(OnStartMeter, CanStartMeter); } return _startMeterCommand; } }   public ICommand AddMinutesCommand { get { if(_addMinutesCommand == null) { _addMinutesCommand = new DelegateCommand<object>(OnAddMinutes, CanAddMinutes); } return _addMinutesCommand; } }   public ICommand ResetCommand { get { if(_resetCommand == null) { _resetCommand = new DelegateCommand<object>(OnResetCommand); } return _resetCommand; } }   } private void OnStartMeter(object obj) { _eventAggregator.GetEvent<TaxiStartedEvent>().Publish( new TaxiStarted() { EngagedOn = DateOfEntry.Value.Date + TimeOfEntry.Value, EngagedState = SelectedState.Value });   _isMeterStarted = true; OnPropertyChanged(this,null); } And views communicate user actions like button clicks, tree view item selections, etc using commands. When user clicks on ‘Start the Meter’ button it invokes the method StartMeterCommand, which calls the method OnStartMeter which publishes the event to TotalViewModel using event aggregator  and TaxiStartedEvent. namespace TaxiModules.ViewModels { public class TotalViewModel:ObservableBase { ... private IEventAggregator _eventAggregator;   public TotalViewModel(IEventAggregator eventAggregator) { _eventAggregator = eventAggregator;   InitializePropertyNames(); InitializeModel(); SubscribeToEvents(); }   public decimal? TotalFare { get { return _totalFare; } set { _totalFare = value; RaisePropertyChanged(_totalFarePropertyName); } } .... private void SubscribeToEvents() { _eventAggregator.GetEvent<TaxiStartedEvent>().Subscribe(OnTaxiStarted, ThreadOption.UIThread,false,(filter) => true); _eventAggregator.GetEvent<TaxiOnMoveEvent>().Subscribe(OnTaxiMove, ThreadOption.UIThread, false, (filter) => true); _eventAggregator.GetEvent<TaxiResetEvent>().Subscribe(OnTaxiReset, ThreadOption.UIThread, false, (filter) => true); }   private void OnTaxiStarted(TaxiStarted taxiStarted) { Fares.Add(new EntryFare()); Fares.Add(new StateTaxFare(taxiStarted)); Fares.Add(new NightSurchargeFare(taxiStarted)); Fares.Add(new PeakHourWeekdayFare(taxiStarted));   SetTotalFare(Fares); }   private void SetTotalFare(IEnumerable<IFare> fares) { TotalFare = (_totalFare ?? 0) + TaxiFareHelper.GetTotalFare(fares); } ....   } }   TotalViewModel subscribes to events, TaxiStartedEvent and rest. When TaxiStartedEvent gets invoked it calls the OnTaxiStarted method which sets the total fare which includes entry fee, state tax, nightly surcharge, peak hour weekday fare.   Note that TotalViewModel derives from ObservableBase which implements the method RaisePropertyChanged which we are invoking in Set of TotalFare property, i.e, once we update the TotalFare property it raises an the event that  allows the TotalFare text box to fetch the new value through the data context. ViewModel is communicating with View through data context and it has no knowledge about View, helping in loose coupling of ViewModel and View.   I have attached the source code (.Net 4.0, Prism 4.0, VS 2010) , download and play with it and don’t forget to leave your comments.  

    Read the article

  • ASP.NET Web API - Screencast series Part 3: Delete and Update

    - by Jon Galloway
    We're continuing a six part series on ASP.NET Web API that accompanies the getting started screencast series. This is an introductory screencast series that walks through from File / New Project to some more advanced scenarios like Custom Validation and Authorization. The screencast videos are all short (3-5 minutes) and the sample code for the series is both available for download and browsable online. I did the screencasts, but the samples were written by the ASP.NET Web API team. In Part 1 we looked at what ASP.NET Web API is, why you'd care, did the File / New Project thing, and did some basic HTTP testing using browser F12 developer tools. In Part 2 we started to build up a sample that returns data from a repository in JSON format via GET methods. In Part 3, we'll start to modify data on the server using DELETE and POST methods. So far we've been looking at GET requests, and the difference between standard browsing in a web browser and navigating an HTTP API isn't quite as clear. Delete is where the difference becomes more obvious. With a "traditional" web page, to delete something'd probably have a form that POSTs a request back to a controller that needs to know that it's really supposed to be deleting something even though POST was really designed to create things, so it does the work and then returns some HTML back to the client that says whether or not the delete succeeded. There's a good amount of plumbing involved in communicating between client and server. That gets a lot easier when we just work with the standard HTTP DELETE verb. Here's how the server side code works: public Comment DeleteComment(int id) { Comment comment; if (!repository.TryGet(id, out comment)) throw new HttpResponseException(HttpStatusCode.NotFound); repository.Delete(id); return comment; } If you look back at the GET /api/comments code in Part 2, you'll see that they start the exact same because the use cases are kind of similar - we're looking up an item by id and either displaying it or deleting it. So the only difference is that this method deletes the comment once it finds it. We don't need to do anything special to handle cases where the id isn't found, as the same HTTP 404 handling works fine here, too. Pretty much all "traditional" browsing uses just two HTTP verbs: GET and POST, so you might not be all that used to DELETE requests and think they're hard. Not so! Here's the jQuery method that calls the /api/comments with the DELETE verb: $(function() { $("a.delete").live('click', function () { var id = $(this).data('comment-id'); $.ajax({ url: "/api/comments/" + id, type: 'DELETE', cache: false, statusCode: { 200: function(data) { viewModel.comments.remove( function(comment) { return comment.ID == data.ID; } ); } } }); return false; }); }); So in order to use the DELETE verb instead of GET, we're just using $.ajax() and setting the type to DELETE. Not hard. But what's that statusCode business? Well, an HTTP status code of 200 is an OK response. Unless our Web API method sets another status (such as by throwing the Not Found exception we saw earlier), the default response status code is HTTP 200 - OK. That makes the jQuery code pretty simple - it calls the Delete action, and if it gets back an HTTP 200, the server-side delete was successful so the comment can be deleted. Adding a new comment uses the POST verb. It starts out looking like an MVC controller action, using model binding to get the new comment from JSON data into a c# model object to add to repository, but there are some interesting differences. public HttpResponseMessage<Comment> PostComment(Comment comment) { comment = repository.Add(comment); var response = new HttpResponseMessage<Comment>(comment, HttpStatusCode.Created); response.Headers.Location = new Uri(Request.RequestUri, "/api/comments/" + comment.ID.ToString()); return response; } First off, the POST method is returning an HttpResponseMessage<Comment>. In the GET methods earlier, we were just returning a JSON payload with an HTTP 200 OK, so we could just return the  model object and Web API would wrap it up in an HttpResponseMessage with that HTTP 200 for us (much as ASP.NET MVC controller actions can return strings, and they'll be automatically wrapped in a ContentResult). When we're creating a new comment, though, we want to follow standard REST practices and return the URL that points to the newly created comment in the Location header, and we can do that by explicitly creating that HttpResposeMessage and then setting the header information. And here's a key point - by using HTTP standard status codes and headers, our response payload doesn't need to explain any context - the client can see from the status code that the POST succeeded, the location header tells it where to get it, and all it needs in the JSON payload is the actual content. Note: This is a simplified sample. Among other things, you'll need to consider security and authorization in your Web API's, and especially in methods that allow creating or deleting data. We'll look at authorization in Part 6. As for security, you'll want to consider things like mass assignment if binding directly to model objects, etc. In Part 4, we'll extend on our simple querying methods form Part 2, adding in support for paging and querying.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >