Network Programming Archives | CodeGuru https://www.codeguru.com/network/ Sat, 07 May 2022 17:27:48 +0000 en-US hourly 1 https://wordpress.org/?v=6.3.2 Configuring Security Rules In Azure Firewall https://www.codeguru.com/azure/security-rules-azure/ Sat, 07 May 2022 17:22:15 +0000 https://www.codeguru.com/?p=19222 Azure Firewall is a Microsoft-managed network virtual appliance (NVA) that provides the best of breed threat protection for cloud workloads running in Azure. It is a cloud-native and intelligent network firewall security service that allows developers and network administrators to centrally create, enforce, and monitor network security policies in virtual networks. In this cloud development […]

The post Configuring Security Rules In Azure Firewall appeared first on CodeGuru.

]]>
Azure Firewall is a Microsoft-managed network virtual appliance (NVA) that provides the best of breed threat protection for cloud workloads running in Azure. It is a cloud-native and intelligent network firewall security service that allows developers and network administrators to centrally create, enforce, and monitor network security policies in virtual networks. In this cloud development tutorial, we will demonstrate how to configure Azure to achieve high security and protection across a network.

Read: How to Create an Azure File Sync Service

How to Configure Azure Firewall

To begin learning how to configure Azure Firewall, we have to first create a virtual network. To do so, login to Azure Portal and search for the phrase Virtual Networks.

Create a Virtual Network in Azure Firewall

Click Create Virtual Network, select your Subscription and Resource Group. If you do not have one, go ahead and create a new Resource Group.

Create a Resource Group in Azure Firewall

Next, add the name of your virtual network and select Region.

Virtual Network Basic Details in Azure Firewall

Click Next and then add or update your IP addresses:

Add IP Address to a Virtual Network in Azure Firewall

Read: Azure Storage Account Replication Types

Then, in the Security tab, select the following options, as depicted in the next image:

Azure Virtual Network Security Options

Click on the Review + Create tab, then click Create.

Create a Virtual Network in Azure Firewall

Wait for your deployment to complete. Once finished, click on Go to Resource.

Deploy a Virtual Network in Azure Firewall

Choose + Subnet Link to a Subnet in the newly created virtual network.

Virtual Network Subnets in Azure Firewall

Add all the details required for the subnet and save it. You will now have two subnets under the newly created virtual network.

Azure Firewall Subnet Options

Azure Firewall Subnet Created

Read: Configuring Load Balancer in Azure

How to Create a New Firewall in Azure Firewall

Next, we will need to create a new firewall. Search for the phrase Firewall in the Azure Portal and click Create.

Create a New Firewall in Azure Firewall

Add the name of the firewall, then select the Region, Resource Group, and Availability Zone.

Add Azure Firewall Details

After this, we will want to select Firewall Tier Standard and then Firewall Management: Use a Firewall Policy to Manage This Firewall or create a new firewall policy, as depicted below:

Azure Firewall Policies

Select the previously created virtual network and update the IP Address space.

Azure Firewall Address Space

Next, create a Public IP or select an existing one if unused.

Create an Azure Firewall Public IP Address

After adding all of the basic firewall details, the screen will look like the image below:

Azure Firewall Details and Options

Finally, click Review + Create. Review all of the provided details to make sure they are accurate and create the firewall.

Azure Firewall tutorial

Now we have successfully deployed the Azure Firewall within our firewall. Take note of the Firewall Private IP, Firewall SKU, and the Firewall Subnet.

Read more Microsoft Azure tutorials and cloud development guides.

The post Configuring Security Rules In Azure Firewall appeared first on CodeGuru.

]]>
Implementing Circuit Breaker Using Polly https://www.codeguru.com/network/circuit-breaker-polly/ Wed, 26 Jan 2022 01:42:59 +0000 https://www.codeguru.com/?p=18867 Applications need to communicate with many other services and components to function properly. During this communication, temporary faults may arise due to some of the services or components being unable to respond on time. These faults can come in the form of timeouts, overloaded resources, networking hiccups, and so on. Retry and circuit-breaker patterns are […]

The post Implementing Circuit Breaker Using Polly appeared first on CodeGuru.

]]>
Applications need to communicate with many other services and components to function properly. During this communication, temporary faults may arise due to some of the services or components being unable to respond on time. These faults can come in the form of timeouts, overloaded resources, networking hiccups, and so on. Retry and circuit-breaker patterns are useful for solving these temporary faults. In fact, these are the most common approaches when coding for resiliency.

In this article, developers will create a simple example to demonstrate how to use Polly to implement both retry and circuit-breaker policies.

What is Retry in .NET?

Retry in .NET terms basically means “if something goes wrong, try repeating the same operation again for a certain number of times before giving up.” One example of this might be your service calling a third-party API, failing, and then retrying again until a connection is made or until 10 attempts have been made.

What is a Circuit-breaker Pattern in .NET?

A circuit-breaker pattern in .NET programming basically says “if something goes wrong, hit the panic button that prevents any further attempts to repeat the operation.” An example of a circuit-breaker pattern might be an overloaded database that you want your program to quit querying if an overload is detected or occurs.

Polly .NET Circuit-breaker pattern
Image Courtesy of Microsoft Docs

Read: Step-by-step Guide to Developing a SOHO HTTP Filter

What is Polly in .NET?

Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as retry, circuit breaker, timeout, bulkhead isolation, and so forth. It is a mature library that is almost synonymous with app resiliency.

How to Implement Polly

Implementing a retry pattern with an HTTP(s) request with .NET is very easy; all developers need to do is write an extension method named AddPolicyHandler in order to add the retry policy for the HttpClient. Refer to the following code snippet to see how this is achieved. Note that the GetRetryPolicy method will be invoked during network failures or if HTTP errors are triggered.

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient("MysampleClient")
        .SetHandlerLifetime(TimeSpan.FromMinutes(10))
        .AddPolicyHandler(GetRetryPolicy())
        ;

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

private IAsyncPolicy GetRetryPolicy()
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
        .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)))
        ;
}

Next, the following code snippet demonstrates how to run the above code in a controller; the behavior will be the same when we use HttpClient:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IHttpClientFactory _clientFactory;
    public ValuesController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
  
    [HttpGet]
    public async Task GetAsync()
    {  
        var url = $"https://www.mywebsite.com/homepage";
        var client = _clientFactory.CreateClient("MysampleClient");
        var response = await client.GetAsync(url);
        var result = await response.Content.ReadAsStringAsync();
        return result;
    }
}

Read: Consuming an ASP.NET Web API Using HttpClient

How to Push a Message in a Message Queue in .NET

The .NET code below demonstrates how to push the message in a message queue:

Route("api/[controller]")]  
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public ActionResult<IEnumerable> Get()
    {
        var message = Encoding.UTF8.GetBytes("My retry pattern");

        var retry = Policy
            .Handle()
            .WaitAndRetry(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));

        try
        {
            retry.Execute(() =>
            {
                Console.WriteLine($"begin at {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.");
                var factory = new ConnectionFactory
                {
                    HostName = "localhost",
                    UserName = "Test",
                    Password = "Tes"
                };

                var connection = factory.CreateConnection();
                var model = connection.CreateModel();
                model.ExchangeDeclare("retrypattern", ExchangeType.Topic, true, false, null);
                model.BasicPublish("retrypattern", "retrypattern.#", false, null, message);
            });
        }
        catch
        {
            Console.WriteLine("exception here.");
        }

        return new string[] { "TestValue1", "TestValue2" };
    }
}

Conclusion to Implementing Circuit-breaker with Polly and .NET

In this article, we have introduced Polly circuit breaker policies and showed how to use them with a .NET application that uses the HttpClientFactory pattern to create instances of HttpClient. Be sure to check back often for more .NET programming tutorials and developer articles.

The post Implementing Circuit Breaker Using Polly appeared first on CodeGuru.

]]>
Cloud Computing Types Overview https://www.codeguru.com/azure/cloud-computing-types/ Thu, 07 Oct 2021 17:25:09 +0000 https://www.codeguru.com/?p=18592 Cloud computing is a hot topic among developers, filling the conversation in every field of information technology and business. There is a lot of misunderstanding when it comes to the types of cloud computing and the cloud in general between non-specialists and even among some veteran technology specialists. In today’s cloud computing tutorial, we seek […]

The post Cloud Computing Types Overview appeared first on CodeGuru.

]]>
Cloud Computing Tutorials

Cloud computing is a hot topic among developers, filling the conversation in every field of information technology and business. There is a lot of misunderstanding when it comes to the types of cloud computing and the cloud in general between non-specialists and even among some veteran technology specialists. In today’s cloud computing tutorial, we seek to clear up some of the confusion by defining the different types of cloud computing services.

Despite the fact that cloud computing has become an established technology over the past few years, it is still not easily available or free to the public in the same way that web hosting is. This may explain some of the reason why it is still misunderstood and most often confined to the role of cloud backup storage.

Up to this point in time, there are many businesses and companies that have not moved to the cloud, especially in developing countries and sensitive sectors such as financial, medical, government, and the military branches.

Despite the expectations, there are, in reality, some situations where the user still prefers on-premise solutions such as personal desktop computers versus cloud computer desktop services. There are also some states that put restrictions on companies, preventing them from moving to cloud servers outside the state for sovereign reasons.

With all of that in mind, let’s begin our journey to better understand what cloud computing is and how it applies to developers, programmers, and those in the information technology (IT) realm. We will also look at some of the more popular cloud services for developers.

What is Cloud Computing?

To begin, it is worth quickly offering a definition for cloud computing, if nothing else to make sure we eliminate some widespread stereotypes associated with the term. The most common thought about cloud computing is that it is just some kind of backup storage application. While that is technically correct – backup storage is one use of cloud computing – it is just one in a million of the different and wide variety of modern ways cloud computing is used.

Cloud tech technology is a versatile concept for a variety of terms like cloud computing, cloud infrastructure, cloud database, cloud storage, cloud-based, cloud server, and so forth. Simply put, it begins by using online remote resources (hardware and software functions) as a service in the sky (metaphorically). Although it is supposed to use the same computing physical hardware and software as regular servers, it has a different modern architecture to better suit servers’ availability and distribution over the Internet around the world.

Advantages of Cloud Computing

From securing cloud backup storage to enjoying sync apps across different devices, cloud computing is not confined only to such individual usage. At the business level, the advantages and use cases are more clear and numerous, especially in terms of reducing cost and minimizing capital expenditure.

Some examples of the benefits of cloud computing include:

  • Cut part of the operational costs for hardware, databases, servers, and software.
  • Get 24/7 uptime support and turn-to-zero probability of downtime.
  • Ability to scale resources up and down as needed all at once.
  • Stop worrying about any maintainability and updates; these are handled by the provider.
  • Getting data centers in any location as the business needs to increase speed and reliability.

Cloud Computing Types and Models

Cloud types are typically categorized into two kinds of classification: Cloud Delivery Model and Cloud Deployment Model. In the Deployment Model, the resources are the same but the difference is in location and ownership. While in the Delivery Model there are different levels for distribution of responsibility between the provider and the user.

Deployment Model

There are four main types of cloud computing based on the Deployment Model:

  • Private clouds: Cloud environments solely dedicated to a single end-user or company. It is used for private and sensitive sectors.
  • Public clouds: Pooled cloud environments shared for many users or companies. It keeps a good amount of privacy and independence and is less expensive.
  • Hybrid clouds: Contains both private cloud and public clouds models connected through local area networks. It is for users who have some usual and special needs.
  • Multiclouds: It is made from more than one cloud service and provider. Multiclouds are not hybrid clouds because they are separated. It is used for sensitive data and information.

Delivery Model

There are also four main types of cloud computing services based on the Delivery Model:

Infrastructure as Service (IaaS): Provides cloud computing at the level of fundamental infrastructure either as a real bare metal server or dedicated virtual server, in addition to the network and data storage. The user can install any operating system and application of their choice. The infrastructure update and maintenance are the provider’s responsibility, but the user is responsible for updating his OS and applications.

Platforms as a Service (PaaS): Here, the provider is responsible for infrastructure, operating system, and software framework. The user can install or develop their own applications. It is an ideal choice for developing web applications, where many developers can work together.

Software as a Service (SaaS): In this solution, the provider is responsible for nearly everything down to the software. The user has only the end service via paid subscription. It’s a great choice for CRM and mobile applications sales software. No need for worrying about anything which makes it also suitable for short-term projects.

Function as a Service (FaaS) or serverless computing: For providing solutions that run code separately. It’s a great choice to make essential application tasks that run with no need for coding them in the user applications, which makes it easier to maintain and develop them with lower cost and cloud usage.

In all of these options flexibility, reliability, and scalability are considered main features. That also helps to reduce the burden of office hardware and even the software in the (SaaS) option. Also, with pay-for-use features, it has become an ideal cost-effective IT solution for business growth – especially for startups.

Many sectors can get great benefits from cloud computing. The sectors that can benefit the most from the cloud IT revolution include:

  • Banking & Finance
  • Government
  • Search engines
  • Manufacturing
  • Robots and IoT
  • Artificial intelligence
  • Healthcare
  • Education
  • Software development
  • Web hosting
  • Pharmaceutical
  • Transport
  • Tourism
  • Real estate
  • IT/ITES

Cloud Service Providers for Developers

There are a lot of cloud service providers, but the top ten of are:

The post Cloud Computing Types Overview appeared first on CodeGuru.

]]>
“Some Day”: 1984: An Editorial on the Future of Computers https://www.codeguru.com/news/future-of-computers/ Tue, 24 Aug 2021 18:04:42 +0000 https://www.codeguru.com/?p=18452 Like many developers, I have shelves of books that I consider important to have within reach should I need them. While there are tons of resources online, there are a number of classics that are worth having on the shelf within easy reach. These include some of the books I wrote as well so that […]

The post “Some Day”: 1984: An Editorial on the Future of Computers appeared first on CodeGuru.

]]>
Future of Compting

Like many developers, I have shelves of books that I consider important to have within reach should I need them. While there are tons of resources online, there are a number of classics that are worth having on the shelf within easy reach. These include some of the books I wrote as well so that I can remind myself what I knew at one point in the past.

One of the books I found on my shelf caught my attention. It is a book that I picked up from my kids’ school several years ago. The library was tossing it out, so I grabbed it. The book is called Microcomputers at Work by James Hargrove. It’s a kid book of about 45 pages that is so old that it has a pocket in the back for the ‘check out’ card. The book was written in the Orwellian year of 1984, well before the internet and many of today’s modern thrills.

The book includes coverage of a lot of basic concepts that are still relevant today. This includes coverage of chips, disk drives, integrated circuits, processors, and even things like interpreters for “turning BASIC words into computer numbers.” In addition, a bit of history is covered, including a discussion of ENIAC and vacuum tubes.

The Predicted Future of Computers

What was interesting enough to inspire this short article was the ending of the book, where it covers microcomputers in the future. There was a comment about how far computers had come from ENIAC in 1946 to modern times – which was 1984. That was roughly 38 years. Ironically, we are almost 38 years from the time the book was written.

So, what were the predictions for computers?

It was predicted that in the future, computers could have such large memories that “tapes and disks” would not be needed to store information. Clearly, this prediction was found to be very accurate. While people use thumb drives and other memory disks, those tend to be for backing up or sharing data as much as anything. Even then, more people simply use internet connectivity and cloud storage to save, backup, or share information. Clearly, this prediction happened.

Also predicted was that computer languages would become more and more like everyday speech. While there are natural programming languages, I’d say the world has still fallen a little short of being able to simply describe a problem in simple English and get a working program. We are, however, closer than we were 37 years ago. There are languages like Scratch that can use drag and drop widgets to create programs that are nearly as easy as using natural language – something known as low-code and no-code software development.

If you look online, you’ll find that there are languages referred to as natural language programming languages. In many cases, they use English-like syntax but still require a lot of structure to get a working program. These include languages like AppleScript, COBOL, HyperTalk, SenseTalk, and many more. While the area of natural computer languages has evolved, we are not fully there yet. Having said that, with the increases in artificial intelligence (AI) and machine learning (ML), it is easy to predict that this is an area that, in the next 37-38 years, will likely change. In that time frame, I imagine you’ll be able to describe verbally to a computer what you want a program to do, and it will be able to generate the app.

The last prediction made in the book from 1984 will make most people chuckle because of how true it is today:

“Soon, even small computers will have ‘ears.’ One day, you might be able to say: ‘Computer! Do you think we’ll have snow tonight or an earthquake?’ and get an answer.”

Simply substitute “Computer” with “Siri,” “Okay Google,” or “Cortana,” and you’ll get the answer along with many more details. I doubt in 1984 they fully comprehended how “small” a small computer would be, nor that the level of weather predicting would be at the level it currently is due to what computers and computer modeling can do.

The Orwellian Predictions

Of course, these predictions were written in the year 1984. It might be that in 1949, the predictions of where computers were headed might have been more accurate. With the predictions of history being rewritten and technology being able to track every move of people, it could easily be said that three or four decades before 1984, Orwell had a better idea of what the future of computing would be able to do.

Predicting the Future of Computing

Of course, it could be silly to try to predict where computing will be in 37 to 38 years from today. I’m not sure how many people would have predicted in 1984 the level of connectivity we have in today’s world. We live in a world where many minor things are connected as a result of computers. For example, the tires in some of our cars tell the car when they are low, and the cars tell the driver (and others) when they need service. We live in a world that has shoes that can track the number of steps taken by the wearer. We have devices that let you pay for services by simply tapping the device to the register. The power and application of the internet was likely unfathomable by most in 1984, much less the rise of the Internet of Things (Iot).

In the late 1980s, I took a C programming course at Microsoft University on the Microsoft Campus in Redmond, Washington. One of the predictions that the person teaching the course made was that programming would change. It would lead in two directions. Most people would use very high-level languages to create programs – just like what the book predicted. These programmers could be non-technical end-users. In today’s terms, they would be citizen developers. However, there would also be a small group of programmers that would go the opposite direction. They would need to be highly skilled and technical because they would be writing the underlying widgets and code being used by the citizen developers.

Read: C# for Beginners

So, where are computers and software development headed? It is hard to say. With the advent of machine learning (ML), artificial intelligence (AI), connectivity (including wireless communications), improved storage, and hardware optimization, it is clear that things will continue to evolve and get better. With the changes and improvements in areas such as quantum computing, it is clear that the potential for change in the next three or four decades could blow away what was done in the previous 3 or 4.

It’s going to be an interesting ride!

The post “Some Day”: 1984: An Editorial on the Future of Computers appeared first on CodeGuru.

]]>
The XML parsing Article That Should (Not) Be Written! https://www.codeguru.com/network/the-xml-parsing-article-that-should-not-be-written/ Mon, 03 Jan 2011 17:30:21 +0000 https://www.codeguru.com/uncategorized/the-xml-parsing-article-that-should-not-be-written/ Introduction Over the years in my profession as a C++ software developer, I have to infrequently maintain XML file format for some application project files. I found the DOM to be difficult to navigate and use. I have come across many articles and XML libraries which proffer to be easy to use, but none is […]

The post The XML parsing Article That Should (Not) Be Written! appeared first on CodeGuru.

]]>
Introduction

Over the years in my profession as a C++ software developer, I have to infrequently maintain XML file format for some application project files. I found the DOM to be difficult to navigate and use. I have come across many articles and XML libraries which proffer to be easy to use, but none is as easy as the internal XML library co-developed by my ex-coworkers, Srikumar Karaikudi Subramanian and Ali Akber Saifee. Srikumar wrote the 1st version which could only read from XML file and Ali later added the node creation capability which allowed the content to be saved in XML file. However, that library is proprietary. After I left the company, I lost the use of an really-easy-to-use XML library. Unlike many talented programmers out there, I am an idiot; I need an idiot-proof XML library. Too bad, Linq-to-XML (Xinq) is not available in C++/CLI! I decided to re-construct Srikumar’s and Ali’s XML library and made it open-source! I dedicate this article to Srikumar Karaikudi Subramanian and Ali Akber Saifee.

My terrible relationship with Ali Akber Saifee

Ali Akber Saifee and I are what we called “the world’s greatest arch-rivals”. While we worked together in the same company, I would always find every opportunity find ‘flaws’ with Ali and email him to expose some of his ‘problems’ and carbon-copy everyone else. My arch-rival, as always, beat me with some of his best replies. Ali has once offered me a chance for us to make good and work together to conquer the world together. But I rejected his offer (in thinly-veiled plot) to subservient me! The world’s greatest arch-rivals can never work together!

Whenever I lost a friend on facebook, I always check if it was Ali who defriended me. The readers may ask why. Do you, the readers, know the ramifications of the world’s greatest arch-rivals defriend each other on facebook? Ans: there can never be world peace! The readers may ask why the world’s greatest arch-rivals are on each other’s facebook in the 1st place! Well, that is another story for another article in another day!

Why am I rewriting and promoting my arch-rival’s XML library? Before Ali says this, let me pre-empt him and say this myself: Imitation is the most sincere form of flattery. The truth is his XML library is really easy to use!

Some code examples first

<Books>
  <Book>
    <Price>12.990000</Price>
  </Book>
</Books>

To create the above XML, see the C++ code below,

Elmax::Element root;
root.SetDomDoc(pDoc); // A empty DOM doc is initialized beforehand.
root[L"Books"][L"Book"][L"Price"] = 12.99f;

The 3rd line of code detects that the 3 elements do not exist and the float assignment will attempt to create those 3 elements and convert 12.99f to string and assign to the price element. To read the price element, we just assign it to the float variable (see below),

Elmax::Element root;
root.SetDomDoc(pDoc); // A XML file is read into the DOM doc beforehand.
Elmax::Element elemPrice = root[L"Books"][L"Book"][L"Price"];
if(elemPrice.Exists())
    float price = elemPrice;

It is good practice to check if the price element exists, using Exists(), before reading it.

XML versus binary serialization

In this section, let us look first at the advantages of XML over binary serialization before we discuss Elmax. I’ll not discuss XML serialization because I am not familiar with it. Below is the simplified (version 1) file format for a online bookstore.

Version=1
Books
  Book*
    ISBN
    Title
    Price
    AuthorID
Authors
  Author*
    Name
    AuthorID

The child elements are indented under the parent. The elements which can be more than 1 in quantity, are appended with a asterisk(*). The diagram below shows what the (version 1) binary serialization file format will typically look like.

Binary Version 1
Figure 1

Let’s say in the version 2, we add a Description under the Book and a Biography under the Author.

Version=2
Books
  Book*
    ISBN
    Title
    Price
    AuthorID
    Description(new)
Authors
  Author*
    Name
    AuthorID
    Biography(new)

The diagram below shows the version 1 and 2 binary serialization file format. The new additions in version 2 is in lighter colors.

Version 2
Figure 2

Notice the version 1 and 2 are binary incompatible? Below is how binary (note: not binary serialization) file format would choose to implement it.

Version=2
Books
  Book*
    ISBN
    Title
    Price
    AuthorID
Authors
  Author*
    Name
    AuthorID
Description(new)*
Biography(new)*

Binary Version 2
Figure 3

In this way, version 1 of the application still can read the version 2 binary file while ignoring the new additional parts at the back of the file. If XML is used and without doing any work, version 1 of the application still can read the version 2 XML file (forward compatible) while ignoring the new additional elements, provided that the data type of the original elements remains unchanged and not removed. And version 2 application can read version 1 XML file by using the old parsing code (backward compatible). The downside to XML parsing is it is slower than binary file format and takes up more space but XML file are self-describing.

XML Version 2
Figure 4

Below is an example of how I would implement the file format in XML, which is followed by an code example to create the XML file.

<?xml version="1.0" encoding="UTF-8"?>
<All>
  <Version>1</Version>
  <Books>
    <Book ISBN="1111-1111-1111">
      <Title>How not to program!</Title>
      <Price>12.990000</Price>
      <Desc>Learn how not to program from the industry's
worst programmers! Contains lots of code examples which
programmers should avoid! Treat it as inverse education.</Desc>
      <AuthorID>111</AuthorID>
    </Book>
    <Book ISBN="2222-2222-2222">
      <Title>Caught with my pants down</Title>
      <Price>10.000000</Price>
      <Desc>Novel about extra-martial affairs</Desc>
      <AuthorID>111</AuthorID>
    </Book>
  </Books>
  <Authors>
    <Author Name="Wong Shao Voon" AuthorID="111">
      <Bio>World's most funny author!</Bio>
    </Author>
  </Authors>
</All>

#import <msxml6.dll>
using namespace MSXML2;

HRESULT CTryoutDlg::CreateAndInitDom(
    MSXML2::IXMLDOMDocumentPtr& pDoc)
{
    HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
    if (SUCCEEDED(hr))
    {
        // these methods should not fail so don't inspect result
        pDoc->async = VARIANT_FALSE;
        pDoc->validateOnParse = VARIANT_FALSE;
        pDoc->resolveExternals = VARIANT_FALSE;
        MSXML2::IXMLDOMProcessingInstructionPtr pi =
            pDoc->createProcessingInstruction
                (L"xml", L" version='1.0' encoding='UTF-8'");
        pDoc->appendChild(pi);
    }
    return hr;
}

bool CTryoutDlg::SaveXml(
    MSXML2::IXMLDOMDocumentPtr& pDoc,
    const std::wstring& strFilename)
{
    TCHAR szPath[MAX_PATH];

    if(SUCCEEDED(SHGetFolderPath(NULL,
        CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE,
        NULL,
        0,
        szPath)))
    {
        PathAppend(szPath, strFilename.c_str());
    }

    variant_t varFile(szPath);
    return SUCCEEDED(pDoc->save(varFile));
}

void CTryoutDlg::TestWrite()
{
    MSXML2::IXMLDOMDocumentPtr pDoc;
    HRESULT hr = CreateAndInitDom(pDoc);
    if (SUCCEEDED(hr))
    {
        using namespace Elmax;
        using namespace std;
        Element root;
        root.SetConverter(NORMAL_CONV);
        root.SetDomDoc(pDoc);

        Element all = root[L"All"];
        all[L"Version"] = 1;
        Element books = all[L"Books"].CreateNew();
        Element book1 = books[L"Book"].CreateNew();
        book1.Attribute(L"ISBN") = L"1111-1111-1111";
        book1[L"Title"] = L"How not to program!";
        book1[L"Price"] = 12.99f;
        book1[L"Desc"] = L"Learn how not to program from the
industry's worst programmers! Contains lots of code examples
which programmers should avoid! Treat it as inverse education.";
        book1[L"AuthorID"] = 111;

        Element book2 = books[L"Book"].CreateNew();
        book2.Attribute(L"ISBN") = L"2222-2222-2222";
        book2[L"Title"] = L"Caught with my pants down";
        book2[L"Price"] = 10.00f;
        book2[L"Desc"] = L"Novel about extra-martial affairs";
        book2[L"AuthorID"] = 111;

        Element authors = all[L"Authors"].CreateNew();
        Element author = authors[L"Author"].CreateNew();
        author.Attribute(L"Name") = L"Wong Shao Voon";
        author.Attribute(L"AuthorID") = 111;
        author[L"Bio"] = L"World's most funny author!";

        std::wstring strFilename = L"Books.xml";
        SaveXml(pDoc, strFilename);
    }
}

Here is the code to read the XML which is saved in the previous code snippet. Some helper class (DebugPrint) and methods (CreateAndLoadXml and DeleteFile) are omitted to focus on the relevant code. The helper class and methods can be found in the Tryout project in the source code download.

void CTryoutDlg::TestRead()
{
    DebugPrint dp;
    MSXML2::IXMLDOMDocumentPtr pDoc;
    std::wstring strFilename = L"Books.xml";
    HRESULT hr = CreateAndLoadXml(pDoc, strFilename);
    if (SUCCEEDED(hr))
    {
        using namespace Elmax;
        using namespace std;
        Element root;
        root.SetConverter(NORMAL_CONV);
        root.SetDomDoc(pDoc);

        Element all = root[L"All"];
        if(all.Exists()==false)
        {
            dp.Print(L"Error: root does not exists!");
            return;
        }
        dp.Print(L"Version : {0}\n\n", all[L"Version"].GetInt32(0));

        dp.Print(L"Books\n");
        dp.Print(L"=====\n");
        Element books = all[L"Books"];
        if(books.Exists())
        {
            Element::collection_t vecBooks =
                books.GetCollection(L"Book");
            for(size_t i=0; i<vecBooks.size(); ++i)
            {
                dp.Print(L"ISBN: {0}\n",
                    vecBooks[i].Attribute(L"ISBN").GetString(L"Error"));
                dp.Print(L"Title: {0}\n",
                    vecBooks[i][L"Title"].GetString(L"Error"));
                dp.Print(L"Price: {0}\n",
                    vecBooks[i][L"Price"].GetFloat(0.0f));
                dp.Print(L"Desc: {0}\n",
                    vecBooks[i][L"Desc"].GetString(L"Error"));
                dp.Print(L"AuthorID: {0}\n\n",
                    vecBooks[i][L"AuthorID"].GetInt32(-1));
            }
        }

        dp.Print(L"Authors\n");
        dp.Print(L"=======\n");
        Element authors = all[L"Authors"];
        if(authors.Exists())
        {
            Element::collection_t vecAuthors =
                authors.GetCollection(L"Author");
            for(size_t i=0; i<vecAuthors.size(); ++i)
            {
                dp.Print(L"Name: {0}\n",
                    vecAuthors[i].Attribute(L"Name")
                        .GetString(L"Error"));
                dp.Print(L"AuthorID: {0}\n",
                    vecAuthors[i].Attribute(L"AuthorID").GetInt32(-1));
				dp.Print(L"Bio: {0}\n\n",
                    vecAuthors[i][L"Bio"].GetString(L"Error: No bio!"));
            }
        }
    }
    DeleteFile(strFilename);
}

This is the output after the XML is read.

Version : 1

Books
=====
ISBN: 1111-1111-1111
Title: How not to program
Price: 12.990000
Desc: Learn how not to program from the industry's worst programmers! Contains lots of code examples which programmers should avoid! Treat it as reverse education.
AuthorID: 11

ISBN: 2222-2222-2222
Title: Caught with my pants down
Price: 10.000000
Desc: Novel about extra-martial affairs AuthorID: 111 Authors ======= Name: Wong Shao Voon AuthorID: 111 Bio: World's most funny author!

The post The XML parsing Article That Should (Not) Be Written! appeared first on CodeGuru.

]]>
Security Servers Put Microsoft in the Forefront https://www.codeguru.com/network/security-servers-put-microsoft-in-the-forefront/ Fri, 04 Dec 2009 17:17:02 +0000 https://www.codeguru.com/uncategorized/security-servers-put-microsoft-in-the-forefront/ On the heels of this fall’s delivery of Windows 7 and its server complement, Windows Server 2008 Release 2 (R2), Microsoft is now in the process of delivering Forefront security server products aimed at keeping all of those systems secure and running smoothly. Starting today, Microsoft (NASDAQ: MSFT) is shipping a rebranded and updated version […]

The post Security Servers Put Microsoft in the Forefront appeared first on CodeGuru.

]]>

On the heels of this fall’s delivery of Windows 7 and its server complement, Windows Server 2008 Release 2 (R2), Microsoft is now in the process of delivering Forefront security server products aimed at keeping all of those systems secure and running smoothly.

Starting today, Microsoft (NASDAQ: MSFT) is shipping a rebranded and updated version of what was previously called the Internet Security and Acceleration server, or ISA.

Goodbye ISA server, hello Forefront Threat Management Gateway (TMG) 2010.

Likewise, what used to be known as the Intelligent Application Gateway has been renamed Forefront Unified Access Gateway (UAG) 2010, Joel Sider, senior product manager in Microsoft’s core infrastructure marketing group, told InternetNews.com.

UAG 2010 is slated to be released to manufacturing (RTM) in mid-December, and available for sale soon afterwards, Sider added.

The two are part of what used to be code-named the “Stirling” family of enterprise security products, which the company has since branded as Forefront.

“It’s an integrated approach,” Sider said. “Many customers are experiencing what we call ‘security sprawl.'”

The two updated Forefront products, along with a Forefront offering for Exchange Server that shipped last month, are intended to ease those problems for both users and administrators.

“TMG provides new URL filtering, anti-malware, and intrusion-prevention technologies to protect businesses against the latest web-based threats,” members of Microsoft’s Forefront team wrote in a blog on Thursday. “These technologies are integrated with core network protection features such as firewall and VPN to create a unified, easy-to-manage gateway.”

Among the new features added in TMG is an implementation of Microsoft Reputation Services. This is comprised of a Microsoft-hosted, cloud-based system that maintains a centralized database of 45 million Web domains and billions of Web pages to identify and block malicious sites, the company explained.

“There’s no doubt that the risks [of going online] are growing, but blocking all access to the Internet is not an option,” Sider said. “Reputation Services [helps in] assessing whether a site is safe, especially from phishing attacks.”

Meanwhile, Forefront UAG 2010 is designed to provide secure connectivity between corporate networks and remote PCs and mobile devices, via the addition of what Microsoft refers to as Windows DirectAccess.

DirectAccess, which was introduced with Windows 7 and Windows Server 2008 R2, aims to let remote users securely connect to Web sites and enterprise shares, as well as to applications without the use of a virtual private network.

“DirectAccess establishes bi-directional connectivity with a user’s enterprise network every time a user’s DirectAccess-enabled portable computer connects to the Internet, even before the user logs on,” read a post on Microsoft’s TechNet site.

“UAG is built around the idea of giving remote users first-class access to the key resources and network back in the home office,” Sider added.

The post Security Servers Put Microsoft in the Forefront appeared first on CodeGuru.

]]>
E-Mail File Attachment Using MIME (with HTML support) (Plus Authentication) https://www.codeguru.com/network/e-mail-file-attachment-using-mime-with-html-support-plus-authentication/ Mon, 14 Sep 2009 18:23:34 +0000 https://www.codeguru.com/uncategorized/e-mail-file-attachment-using-mime-with-html-support-plus-authentication/ Introduction This is an update of pcouderc’s original article adding the ability to connect to a server with authentication, sending the user and password when stablishing the connection. When a codeguru “afficionado” wants to send automatic mail or needs a mailer for any reason, he may use the classes designed by Wes Clyburn under the […]

The post E-Mail File Attachment Using MIME (with HTML support) (Plus Authentication) appeared first on CodeGuru.

]]>

Introduction

This is an update of pcouderc’s original article adding the ability to connect to a server with authentication, sending the user and password when stablishing the connection.

When a codeguru “afficionado” wants to send automatic mail or needs a mailer for any reason, he may use the classes designed by Wes Clyburn under the title E-Mail file attachment using MIME. See there, where there is a good description of MIME mechanisms and a description of the classes used.

Anyway, there was the need for an update to these classes to add a few more features:


  • Use of HTML text with images.

  • Optimisation of speed due to the use of long strings.

  • Support of CC and BCC.

  • Progess notification for long transfers.

  • Support of BASE64 coding directly from memory (and not only from a file).

With these updates, a nearly full compatibility had been kept. “Nearly” means that the compatibility is at the source level, but the numeric values of some enums has been changed.

Installation


  • Unzip the temail project.

  • Update MYSELF, MAILSERVER, and FROM defines in temail.cpp to your own addresses

  • Compile, build and execute it


You will receive five HTML emails with image and attached file, or not.

Overview

A mail message may contain one or many elementary “parts” : HTML text, GIF image, attached file…

All mail messages are not MIME, but…

A MIME mail message (CMIMEMessage) is considered as having a main MIME part(CMIMEPart), and only one. Some MIME parts are considered as “containers” of some other “elementary” MIME parts. This was not the case with the original classes of Wes, where elementary MIME parts where added to
the message itself: the concept of “container” was implicit but not formalized.

The containers are of type MIXED, ALTERNATIVE, or RELATED (Mmm… you are allowed to ignore all these kind of containers and simply copy the example).

The elementary MIME parts supported are of type TEXT_PLAIN, TEXT_HTML,
APPLICATION_OCTETSTREAM (for attachment), APPLICATION_OCTETSTREAM_IMAGE (for embedded images)

Well, this should be enough to see an example.

Example

void TestHTMLMailWithGifWithAttach()
{
  // Create and initialize a message
  CMIMEMessage *pMsg= new CMIMEMessage;
  pMsg->m_sFrom = FROM;
  pMsg->AddMultipleRecipients(MYSELF);
  pMsg->AddMultipleRecipients("john@brown.family",
                              CMailMessage::BCC);
  pMsg->m_sSubject = "Test CMIMEmessage";
  // Create MIME containers
  CMIMEMessage::CMIMEPart *pMIMEmixed =
        pMsg->AddMIMEPart(CMIMEMessage::MIXED);
  CMIMEMessage::CMIMEPart *pMIMErelated =
        pMIMEmixed->AddMIMEPart(CMIMEMessage::RELATED);
  CMIMEMessage::CMIMEPart *pMIMEalternative =
      pMIMErelated->AddMIMEPart(CMIMEMessage::ALTERNATIVE);
  // Alternative 1 : mail client does not support HTML...

  //      tell it in plain text 7Bits (warning : no
  //      conversion is done)
  CString Text(
"Text that appear when client does not support HTMLrnrn");
  pMIMEalternative->AddMIMEPart(CMIMEMessage::TEXT_PLAIN,Text);
  // Alternative 2 : mail client does support HTML...
  //      tell it in HTML text quoted-printable (warning :
  //      no conversion is done)
  CString Html;
  Html=GetHTMLResource(IDR_HTML1);
  pMIMEalternative->AddMIMEPart(CMIMEMessage::TEXT_HTML,Html);
  // Prepare GIF image

  char* Gif;
  int Len;
  GetGIFResource(IDR_TOLLOGO, &Gif, &Len);
  // GIFS are related to HTML text : note
  //    the string "IDR_TOLLOGO" which appears somewhere
  //    in IDR_HTML1 text
  pMIMErelated->AddMIMEPart(
         CMIMEMessage::APPLICATION_OCTETSTREAM_IMAGE,
         Gif,
         CMIMEMessage::MEMORY,
         "IDR_TOLLOGO",
         Len);
  GetGIFResource(IDR_HR, &Gif, &Len);
  pMIMErelated->AddMIMEPart(
         CMIMEMessage::APPLICATION_OCTETSTREAM_IMAGE,
         Gif,
         CMIMEMessage::MEMORY,
         "IDR_HR",
         Len);
  // Add attachment

  pMIMEmixed->AddMIMEPart(
         CMIMEMessage::APPLICATION_OCTETSTREAM,
         ATTACHMENT);
  // Do not forget to...
  pMsg->FormatMessage();
  // Then ...
  SendSMTP(pMsg);
}

This example should be enough to solve most of the complex cases. On the contrary, simpler cases are possible. See temail.cpp for simpler examples.

Tips

Calling AddMIMEPart()


The parameters of AddMIMEPart() are:

  CMIMEPart* AddMIMEPart(eMIMETypeCode nContentType,
     LPCTSTR szContent= NULL,
     eMIMEEncodingCode nEncoding = DEFAULT,
     LPCTSTR szParameters = NULL,
     int Len=0);

  • nContentType is one of the values seen in the overview.

  • szContent may be the contents of the source of data or a file path to the source of data.

  • nEncoding is one of the following basic values: DEFAULT,_7BIT, QUOTED_PRINTABLE, BASE64. DEFAULT is very fine, but you can try other values. Please note that only BASE64 does effective encoding.


    Other bits may be or’ed with the basic value:

    • MEMORY or FILE indicate the source of data. In the case of FILE szContent contains the file name, else it contains the data itself.

    • SOONCODED and ENCODE indicate if data is soon coded or must be coded by AddMIMEPart.


    Please note the following limitations :
    • In TEXT_PLAIN and TEXT_HTML, BASE64, FILE and ENCODE are not implemented.
    • In APPLICATION_OCTETSTREAM and APPLICATION_OCTETSTREAM_IMAGE, the only implemented basic valueis BASE64. Moreover, SOON_ENCODED is not implemented.


    Please note the default values (when nEncoding is left to DEFAULT):
    • TEXT_PLAIN : _7BIT and SOONCODED and MEMORY.

    • TEXT_HTML : QUOTED_PRINTABLE and SOONCODED and MEMORY.

    • APPLICATION_OCTETSTREAM and APPLICATION_OCTETSTREAM_IMAGE : BASE64 and ENCODE and FILE.


  • szParameters may be used to add some text after the Content-Type except in the case of APPLICATION_OCTETSTREAM or APPLICATION_OCTETSTREAM_IMAGE. In this last case, it contains an identifier string for the image
    (cf IDR_TOLLOGO in the example).
  • Len indicates the length of szContent. In case of 0, a strlen is done.

Progress notification

Derive you own class from CMIMEmessage and override NotifyProgress(). For a basic example search CNotifiedMIMEMessage in temain.c.

To do



  • Test better : the mailer has been tested only with Outlook express 5.

  • No conversion are done except binary BASE64 for attached files and images.
  • Credits


    These classes come directly from the work of Wes Clyburn and pcouderc.

    The post E-Mail File Attachment Using MIME (with HTML support) (Plus Authentication) appeared first on CodeGuru.

    ]]>
    Working with Forms https://www.codeguru.com/network/working-with-forms/ Tue, 24 Jun 2008 16:47:12 +0000 https://www.codeguru.com/uncategorized/working-with-forms/ The following is Chapter 4 from Wicked Cool PHP by William Steinmetz with Brian Ward. Reprinted with permission. Security Measures: Forms Are Not Trustworthy A common mistake that novices make is to trust the data provided by an HTML form. If you have a drop-down menu that only allows the user to enter one of […]

    The post Working with Forms appeared first on CodeGuru.

    ]]>

    The following is Chapter 4 from Wicked Cool PHP by William Steinmetz with Brian Ward. Reprinted with permission.

    Security Measures: Forms Are Not Trustworthy

    A common mistake that novices make is to trust the data provided by an HTML form. If you have a drop-down menu that only allows the user to enter one of three values, you must still check those values. You also cannot rely on JavaScript to stop people from sending whatever they like to your server.

    Your site’s users can write their own form in HTML to use against your server; users can also bypass the browser entirely and use automatic tools to interact with web scripts. You should assume that people will mess around with parameters when you put a script on the Web, because they might be trying to discover an easier way to use your site (though they could be attempting something altogether less beneficial).

    To ensure that your server is safe, you must verify all data that your scripts receive.

    Verification Strategies

    There are two approaches to checking form data: blacklisting and whitelisting.

    Blacklisting is the process of trying to filter out all bad data by assuming that form submissions are valid and then explicitly seeking out bad data. In general, this technique is ineffective and inefficient. For example, let’s say that you’re trying to eliminate all “bad” characters from a string, such as quotes. You might search for and replace quotation marks, but the problem is that there will always be bad characters you didn’t think of. In general, blacklisting assumes that most of the data you receive is friendly.

    A better assumption to make about form data you’re receiving is that it’s inherently malicious; thus, you should filter your data in order to accept only valid data submissions. This technique is called whitelisting. For example, if a string should consist of only alphanumeric characters, then you can check it against a regular expression that matches only an entire string of A-Za-z0-9. Whitelisting may also include forcing data to a known range of values or changing the type of a value. Here is an overview of a few specific tactics:

    • If the value should be a number, use the is_numeric() function to verify the value. You can force a value to an integer using the intval() function. If the value should be an array, use is_array().
    • If the value should be a string, use is_string(). To force it, use strval().
    • If the value should be null, use is_null().
    • If the value should be defined, use isset().
    WHITELISTING INTEGERS

    Here’s a typical example of how you might whitelist for a numeric value. If the data is not numeric, then you use a default value of zero (of course, this assumes that zero is an acceptable value):

    if (! is_numeric($data)) { //
       Use a default of 0.
       $data = 0;
    }
    

    In the case of integers, there is an alternative if you know that all integer values are safe. Using $data = intval($data); forces $data to its integral value. This technique is called typecasting.

    Using $_POST, $_GET, $_REQUEST, and $_FILES to Access Form Data

    In Chapter 2, we showed you how to turn off the register_globals setting that automatically sets global variables based on form data.

    To shut down this dangerous setting, refer to “#14: Turning Off Registered Global Variables” on page 25. How do you use $_POST, $_FILES, and $_GET to retrieve form data? Read on.

    #25: Fetching Form Variables Consistently and Safely

    You should pull form data from predefined server variables. All data passed on to your web page via a posted form is automatically stored in a large array called $_POST, and all GET data is stored in a large array called $_GET. File upload information is stored in a special array called $_FILES (see “#54: Uploading Images to a Directory” on page 97 for more information on files). In addition, there is a combined variable called $_REQUEST.

    To access the username field from a POST method form, use $_POST['username']. Use $_GET['username'] if the username is in the URL. If you don’t care where the value came from, use $_REQUEST['username'].

    <?php
    
    $post_value = $_POST['post_value'];
    $get_value = $_GET['get_value'];
    $some_variable = $_REQUEST['some_value'];
    
    ?>
    

    $_REQUEST is a union of the $_GET, $_POST, and $_COOKIE arrays. If you have two or more values of the same parameter name, be careful of which one PHP uses. The default order is cookie, POST, then GET.

    There has been some debate on how safe $_REQUEST is, but there shouldn’t be. Because all of its sources come from the outside world (the user’s browser), you need to verify everything in this array that you plan to use, just as you would with the other predefined arrays. The only problems you might have are confusing bugs that might pop up as a result of cookies being included.

    Trimming Excess Whitespace

    Excess whitespace is a constant problem when working with form data. The trim() function is usually the first tool a programmer turns to, because it removes any excess spaces from the beginning or end of a string. For example, “Wicked Cool PHP                  ” becomes “Wicked Cool PHP.” In fact, it’s so handy that you may find yourself using it on almost every available piece of user-inputted, non-array data:

    $user_input = trim($user_input);

    But sometimes you have excessive whitespace inside a string—when someone may be cutting and copying information from an email, for instance. In that case, you can replace multiple spaces and other whitespace with a single space by using the preg_replace() function. The reg stands for regular expression, a powerful form of pattern matching that you will see several times in this chapter.

    <?php
    function remove_whitespace($string) {
       $string = preg_replace('/\s+/', ' ', $string);
       $string = trim($string);
       return $string;
    }
    ?>
    

    You’ll find many uses for this script outside of form verification. It’s great for cleaning up data that comes from other external sources.

    #27: Importing Form Variables into an Array

    One of the handiest tricks you can use in PHP is not actually a PHP trick but an HTML trick. When a user fills out a form, you’ll frequently check the values of several checkboxes. For example, let’s say you’re taking a survey to see what sorts of movies your site’s visitors like, and you’d like to automatically insert those values into a database called customer_preferences. The hard way to do that is to give each checkbox a separate name on the HTML form, as shown here:

    <p>What movies do you like?</p>
    <input type="checkbox" name="action"  value="yes"> Action
    <input type="checkbox" name="drama"   value="yes"> Drama
    <input type="checkbox" name="comedy"  value="yes"> Comedy
    <input type="checkbox" name="romance" value="yes"> Romance
    

    Unfortunately, when you process the form on the next page, you’ll need a series of if/then loops to check the data—one loop to check the value of $action, one to check the value of $drama, and so forth. Adding a new checkbox to the HTML form results in yet another if/then loop to the processing page.

    A great way to simplify this procedure is to store all of the checkbox values in a single array by adding [] after the name, like this:

    <form action="process.php" method="post">
    <p>What is your name?</p>
    <p><input type="text" name="customer_name"></p>
    
    <p>What movies do you like?</p>
    <p>
       <input type="checkbox" name="movie_type[]" value="action">  Action
       <input type="checkbox" name="movie_type[]" value="drama">   Drama
       <input type="checkbox" name="movie_type[]" value="comedy">  Comedy
       <input type="checkbox" name="movie_type[]" value="romance"> Romance
    </p>
    <input type="submit">
    </form>
    

    When PHP gets the data from a form like this, it stores the checked values in a single array. You can loop through the array this way:

    <?php
    $movie_type = $_POST["movie_type"];
    $customer_name = strval($_POST["customer_name"]);
    
    if (is_array($movie_type)) {
       foreach ($movie_type as $key => $value) {
          print "$customer_name likes $value movies.<br>"; }
    }
    
    ?>
    

    Not only does this technique work for checkboxes, but it’s extremely handy for processing arbitrary numbers of rows. For example, let’s say we have a shopping menu where we want to show all the items in a given category. Although we may not know how many items will be in a category, the customer should be able to enter a quantity into a text box for all items he wants to buy and add all of the items with a single click. The menu would look like Figure 4-1.

    Figure 4-1: A form with an array of checkboxes

    Let’s access product name and ID data in the product_info MySQL table described in the appendix to build the form as follows:

    <?php
    /* Insert code for connecting to $db here. */
    
    $category = "shoes";
    /* Retrieve products from the database. */
    $sql = "SELECT product_name, product_id FROM product_info
       WHERE category = '$category'";
    
    $result = @mysql_query($sql, $db) or die;
    
    /* Initialize variables. */
    $order_form = ""; /* Will contain product form data */
    $i = 1;
    
    print '<form action="addtocart.php" method="post">';
    
    while($row = mysql_fetch_array($result)) {
       // Loop through the results from the MySQL query.
       $product_name = stripslashes($row['product_name']);
       $product_id = $row['product_id'];
    
       // Add the row to the order form.
       print "<input type=\"hidden\" name=\"product_id[$i]\"
          value=\"$product_id\ ">";
       print "<input type=\"text\" name=\"quantity[$i]\"
       size=\"2\" value=\"0\"> $product_name<br />";
    
       +1
    )
    print '<input type="submit" name="add" value="Add to Cart"></form>'
    
    ?>
    

    The processing script addtocart.php is as follows:

    <?php
    
    $product_id = $_POST["product_id"];
    $quantity = $_POST[" quantity tyle='"];
    
    if (is_array($quantity)) {
       foreach ($quantity as $key => $item_qty) {
          $item_qty = intval($item_qty);
          if ($item_qty > 0) {
             $id = $product_id[$key];
             print "You added $item_qty of Product ID $id.<br>"; }
       }
    }
    
    ?>
    

    As you can see, this script depends wholly on using the index from the $quantity array ($key) for the $product_id array.

    The post Working with Forms appeared first on CodeGuru.

    ]]>
    PHP Tip: Validating a Credit Card https://www.codeguru.com/network/php-tip-validating-a-credit-card/ Wed, 18 Jun 2008 16:39:31 +0000 https://www.codeguru.com/uncategorized/php-tip-validating-a-credit-card/ The following is tip #30 from Wicked Cool PHP by WIlliam Steinmetz with Brian Ward. Reprinted with permission. Here’s a brief overview of how online credit card transactions work. First, you need to find a merchant solution (an online provider, such as Authorize.net or Secpay.com) that provides you with a merchant account. This account is […]

    The post PHP Tip: Validating a Credit Card appeared first on CodeGuru.

    ]]>

    The following is tip #30 from Wicked Cool PHP by WIlliam Steinmetz with Brian Ward. Reprinted with permission.

    Here’s a brief overview of how online credit card transactions work. First, you need to find a merchant solution (an online provider, such as Authorize.net or Secpay.com) that provides you with a merchant account. This account is like a bank account, except that it allows you to process charges for credit card transactions. The merchant provider typically charges a per-transaction fee for each credit card action.

    If you have a physical store that accepts credit cards, you almost certainly have a merchant solution. However, not all merchant solutions offer online transactions. The ones that do offer online transactions give you access to a payment gateway, a secure server for processing credit card charges. Usually, the transactions occur via an XML datastream. You can use cURL to exchange XML with the payment gateway (see Chapter 11 of Wicked Cool PHP for more details).

    However, you can do some preliminary form validation work before talking to the payment gateway to save on transactions and transaction fees and possibly speed things for the user if they typed their credit card number incorrectly. It turns out that you can weed out completely incorrect credit card numbers with an easy algorithm. Furthermore, you can even determine a credit card type from a valid number. Keep in mind, though, that passing these tests is no guarantee that a card isn’t stolen or canceled or that it belongs to a different person.


    <?php
    function validate_cc_number($cc_number) {
       /* Validate; return value is card type if valid. */
       $false = false;
       $card_type = "";
       $card_regexes = array(
          "/^4d{12}(ddd){0,1}$/" => "visa",
          "/^5[12345]d{14}$/"       => "mastercard",
          "/^3[47]d{13}$/"          => "amex",
          "/^6011d{12}$/"           => "discover",
          "/^30[012345]d{11}$/"     => "diners",
          "/^3[68]d{12}$/"          => "diners",
       );
    
       foreach ($card_regexes as $regex => $type) {
           if (preg_match($regex, $cc_number)) {
               $card_type = $type;
               break;
           }
       }
    
       if (!$card_type) {
           return $false;
       }
    
       /*  mod 10 checksum algorithm  */
       $revcode = strrev($cc_number);
       $checksum = 0;
    
       for ($i = 0; $i < strlen($revcode); $i++) {
           $current_num = intval($revcode[$i]);
           if($i & 1) {  /* Odd  position */
              $current_num *= 2;
           }
           /* Split digits and add. */
               $checksum += $current_num % 10; if
           ($current_num >  9) {
               $checksum += 1;
           }
       }
    
       if ($checksum % 10 == 0) {
           return $card_type;
       } else {
           return $false;
       }
    }
    
    ?>
    

    This function has two main stages. The first determines card type, and the second determines whether the card checksum is correct. If the card passes both tests, the return value is the card type as a string. If a card is invalid, you get false (you can change this return value to whatever you like with the $false variable).

    The first stage is where the big trick comes in, where we determine the card type and confirm the prefix in one quick step. Credit card numbers follow a certain format. For example, all Visas start with 4 and have 13 or 16 digits, all MasterCards start with 51 through 55 and have 16 digits, and all American Express cards start with 34 or 37 and have 15 digits. These rules are easily expressed in a few regular expressions, and because they are unique rules, we can map the regular expressions to card types in an array called $card_regexes. To check for a valid format, we just cycle through the regular expressions until one matches. When we get a match, we set $card_type and move to the next stage. If no expressions match, we return failure.

    The checksum test for the credit card number uses a mod 10 algorithm, a reasonably simple-to-implement check that does the following:


    • It starts with a checksum value of 0.

    • It runs through the credit card number digit-by-digit from right to left.

    • If the current digit has an odd index (that is, every other digit, starting at index 0), the digit is doubled. If the value of the doubled digit is over 9, the two numbers are added together and added to the checksum (so an 8 becomes 16, which becomes 1 + 6, which becomes 7). Otherwise the current (doubled if on an odd index) digit is added to the checksum.

    • After running through all the digits, the final checksum must be divisible by 10. If not, the number fails the test.

    There are several ways to code this algorithm; the implementation here is on the compact side, but easy enough to follow.

    The post PHP Tip: Validating a Credit Card appeared first on CodeGuru.

    ]]>
    Wt: C++ Web Toolkit Library Lets You Write Scripting-Independent Web Apps https://www.codeguru.com/network/wt-c-web-toolkit-library-lets-you-write-scripting-independent-web-apps/ Fri, 06 Jun 2008 21:47:00 +0000 https://www.codeguru.com/uncategorized/wt-c-web-toolkit-library-lets-you-write-scripting-independent-web-apps/ Wt (pronounced ‘witty’) is a C++ library and application server for developing and deploying web applications. Although Wt supplies a GUI, it is not your typical “framework”, which locks you into someone’s preconceived idea of how applications should be structured. Rather, Wt is widget-centric, and although inspired by existing C++ GUIs, it offers complete abstraction […]

    The post Wt: C++ Web Toolkit Library Lets You Write Scripting-Independent Web Apps appeared first on CodeGuru.

    ]]>
    Wt (pronounced ‘witty’) is a C++ library and application server for developing and deploying web applications. Although Wt supplies a GUI, it is not your typical “framework”, which locks you into someone’s preconceived idea of how applications should be structured. Rather, Wt is widget-centric, and although inspired by existing C++ GUIs, it offers complete abstraction of any web-specific implementation details, all the way down to event handling and graphics support. It’s probably not a coincidence that Wt is named similarly to the ever-popular Qt application development system!

    In fact, none of today’s so-called “page-based frameworks” (built on PHP or JSP/JSF derivatives) for developing web applications make abstraction of the peculiarities of the underlying implementation technologies. As a consequence, a developer must gain familiarity with a panoply of ever-changing technologies, including HTML/XHTML, JavaScript, CSS, AJAX, CGI, DHTML, SVG/VML/Canvas—just to name a few. Moreover, as soon as you drive a stick into the ground and choose a technology such as AJAX or JavaScript, you must take responsibility for graceful degradation when these pieces are missing in action due to or disabled for local security reasons. Little has changed in the structure of applications that follow the primarily page-centric paradigm of 1990s HTML. This means that you will need to design and maintain manually your client-server communication when using advanced AJAX techniques.

    Generating HTML code or filling HTML templates is prone to security problems such as Cross-Site-Scripting (XSS), by unwillingly allowing JavaScript to be inserted in the page. Ironically, template frameworks cannot avoid this because as a developer you need to be able to insert self-written JavaScript to improve your web application.

    In contrast, a web application developed with Wt is written in only one compiled language (C++), from which the library generates the necessary HTML/XHTML, JavaScript, CGI, or AJAX code. The responsibility of writing secure and browser-portable web applications is handled by Wt. For example, if available, Wt will maximally use JavaScript and AJAX, but applications developed using Wt will also function correctly when AJAX is not available, or when JavaScript is disabled, reverting to a plain HTML/CGI mechanism for communication between browser and server.

    Typical use scenarios:

    • Web-based GUIs for embedded systems
    • Web-based GUIs that require integration with (existing) C++ libraries
    • Creating a port of existing C++ desktop applications to the web

    Some benefits of using Wt:

    • Develop web applications like you develop C++ desktop applications.
    • Provides plain widgets, which work regardless of JavaScript availability.
    • Enables more polished or advanced functionality when JavaScript is available (without re-coding)
    • Built-in HTTPD and FastCGI for easy development and deployment.
    • A single specification for both client- and server-side validation and event handling (when using stateless slot implementations).
    • Generates standards compliant HTML or XHTML code.
    • Portable, anti-aliased graphics with VML, SVG, or HTML 5.
    • No exposure of business logic, which stays at the server.
    • Page load time is limited only by screen complexity, not application size.

    Installation

    Installing Wt for Windows is a bit harder than implementing it on a Linux host, primarily because there isn’t anything as simple as Linux package management on Windows. So, it becomes a bit of a scavenger hunt, although there is a nice how-to document. Basically, you are responsible for locating the suggested versions of BoostPro Boost library (currently, 1.34.1). BoostPro requires asio, the asynchronous I/O model for C++. This is theoretically included in BoostPro 1.35 although I didn’t test it out. These components in turn require cmake, a freeware “make” type utility.

    Hello Wt!

    You’ll start off with a “hello world” type app that provides a simple CGI type form and see how this design can be realized by a C++ app. Unlike most apps that I write about, you can actually run it for yourself right now on the web! What you’ll see first is a classic web form presentation shown in Figure 1. After you enter your name and click the Submit button (“Greet me.”), it rewrites the page and more-or-less you are back to the initial state, as shown in Figue 2.

    Figure 1: Hello world forms (entering text)

    [Wt2.jpg

    Figure 2: Hello world forms (after clicking Submit)

    So, take a walkthrough of this program and see how it was done. First, keep in mind that most GUI “hello world” apps often run 50 to 100 lines of code.

     1 #include <WApplication>
     2 #include <WBreak>
     3 #include <WContainerWidget>
     4 #include <WLineEdit>
     5 #include <WPushButton>
     6 #include <WText>
     7
     8 using namespace Wt;
     9
    10 class HelloApp : public WApplication
    11 {
    12 public:
    13    HelloApp(const WEnvironment& env);
    14
    15 private:
    16    WLineEdit *nameEdit_;
    17    WText *greeting_;
    18
    19    void greet();
    20 };
    

    The post Wt: C++ Web Toolkit Library Lets You Write Scripting-Independent Web Apps appeared first on CodeGuru.

    ]]>