Search

Index

Revindex Storefront

Export products (Powershell)

Last updated on 2015-04-17 7 mins. to read

The following simple example exports out all the products to an XML file.

# BidOrBuyExport.ps1
#
# This script will export all active products to a XML file.
######################################################################


# Configuration
######################################################################
$APIKey = '0000000-0000-0000-0000-000000000'
$APIUrl = 'http://site.com/DesktopModules/Revindex.Dnn.RevindexStorefront/Api/Rest/V1/ServiceHandler.ashx?portalid=0'
$APIUsername = 'host'

$Condition = 'New'

$FeedFileName = ('Feed.' + [DateTime]::Now.ToString('yyyyMMdd') + '.xml')

$Location = 'Johannesburg'

$LogFileName = ('Log.' + [DateTime]::Now.ToString('yyyyMMdd') + '.txt')

$NetworkTimeout = 30000


# The email(s) to notify on success/error. Separated multiple emails by semicolon.
$NotificationRecipient = 'support@localhost.com'
$NotificationSender = 'support@localhost.com'

$ShippingOption = 'MediumShipping'

$SiteUrl = 'http://site.com'

$SMTPPassword = 'xxxxxx'
$SMTPServer = 'mail.localhost.com'
$SMTPUser = 'mailer'


# The folder to store files, logs, etc. defaults to the current execution path
$WorkingFolder = ((Split-Path $MyInvocation.MyCommand.Path) + '\')


# Functions
######################################################################

# Function to help post HTTP request to web service
Function PostWebRequest([String] $url, [String] $data, [int] $timeout)
{    
    $buffer = [System.Text.Encoding]::UTF8.GetBytes($data)
    [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($url)
    $webRequest.Timeout = $timeout
    $webRequest.Method = "POST"
    $webRequest.ContentType = "application/x-www-form-urlencoded"
    $webRequest.ContentLength = $buffer.Length

    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($buffer, 0, $buffer.Length)
    $requestStream.Flush()
    $requestStream.Close()

    [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
    $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
    $result = $streamReader.ReadToEnd()
    return $result
}


# Function to send email
Function SendEmail([String]$smtpServer, [String] $smtpUser, [String] $smtpPassword, [String] $sender, [String] $recipient, [String] $subject, [String] $body, [String] $attachment)
{
    $msg = New-Object System.Net.Mail.MailMessage
    $msg.From = $sender
    $msg.ReplyTo = $sender
    
    foreach ($r in $recipient.Split(';'))
    {
        if ($r)
        {
            $msg.To.Add($r)
        }
    }
    $msg.subject = $subject
    $msg.body = $body
    
    if ($attachment -and [System.IO.File]::Exists($attachment))
    {
        $att = New-Object System.Net.Mail.Attachment($attachment)
        $msg.Attachments.Add($att)
    }

    $smtp = New-Object System.Net.Mail.SmtpClient($smtpServer)
    $smtp.Credentials = New-Object System.Net.NetworkCredential($smtpUser, $smtpPassword);
    $smtp.Send($msg)
}


# Start program
######################################################################
Try
{  
    # Create feed
    [Xml]$xFeed = [Xml] "<?xml version='1.0' encoding='utf-8'?>
<Root/>"

    $xProducts = $xFeed.CreateElement('Products')
    $xFeed.SelectSingleNode("/Root").AppendChild($xProducts)

# Get categories
$xRequest = [Xml] "<?xml version='1.0' encoding='utf-8'?>
                        <request>
                          <version>1.0</version>
                          <credential>
                            <username>$APIUsername</username>
                            <apiKey>$APIKey</apiKey>
                          </credential>
                          <service>GetCategories</service>
                          <parameters>
                          </parameters>
                        </request>"

[Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
    if ($xResponse.response.code -ne '2000')
    {
        Throw New-Object System.InvalidOperationException("Error executing GetCategories. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
    }
    [System.Xml.XmlElement]$categories = $xResponse.SelectSingleNode('/response/return/categories')

# Get product categories
$xRequest = [Xml] "<?xml version='1.0' encoding='utf-8'?>
                        <request>
                          <version>1.0</version>
                          <credential>
                            <username>$APIUsername</username>
                            <apiKey>$APIKey</apiKey>
                          </credential>
                          <service>GetProductCategoriesByPortal</service>
                          <parameters>
                          </parameters>
                        </request>"

[Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
    if ($xResponse.response.code -ne '2000')
    {
        Throw New-Object System.InvalidOperationException("Error executing GetProductCategories. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
    }
    [System.Xml.XmlElement]$productCategories = $xResponse.SelectSingleNode('/response/return/productCategories')
  
  # Get variants
$xRequest = [Xml] "<?xml version='1.0' encoding='utf-8'?>
                        <request>
                          <version>1.0</version>
                          <credential>
                            <username>$APIUsername</username>
                            <apiKey>$APIKey</apiKey>
                          </credential>
                          <service>GetActiveProductVariantsByPortal</service>
                          <parameters>
                          </parameters>
                        </request>"

    [Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
    if ($xResponse.response.code -ne '2000')
    {
        Throw New-Object System.InvalidOperationException("Error executing GetActiveProductVariantsByPortal. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
    }
    [System.Xml.XmlElement]$productVariants = $xResponse.SelectSingleNode('/response/return/productVariants')
  
    # Get products
    $xRequest = [Xml] "<?xml version='1.0' encoding='utf-8'?>
                        <request>
                          <version>1.0</version>
                          <credential>
                            <username>$APIUsername</username>
                            <apiKey>$APIKey</apiKey>
                          </credential>
                          <service>GetActiveProducts</service>
                          <parameters>
                          </parameters>
                        </request>"

    [Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
    if ($xResponse.response.code -ne '2000')
    {
        Throw New-Object System.InvalidOperationException("Error executing GetActiveProducts. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
    }
    [System.Xml.XmlElement]$products = $xResponse.SelectSingleNode('/response/return/products')

    foreach ($product in $products.SelectNodes('product'))
    {
        # Create feed
        $xProduct = $xFeed.CreateElement('Product')
        $xProducts.AppendChild($xProduct)

        $xProductCode = $xFeed.CreateElement('ProductCode')
        $xProductCode.InnerText = $product.productID
        $xProduct.AppendChild($xProductCode)

$xTitle = $xFeed.CreateElement('Title')
if (![String]::IsNullOrEmpty($product.name))
{
        $xTitle.InnerText = $product.name.locale.GetAttribute("en-US")
}
        $xProduct.AppendChild($xTitle)

# Find first category associated with product
foreach ($productCategory in $productCategories.SelectNodes('productCategory'))
    {
if ($productCategory.productID -eq $product.productID)
{
foreach ($category in $categories.SelectNodes('category'))
    {
if ($category.categoryID -eq $productCategory.categoryID)
{
$xCategory = $xFeed.CreateElement('Category')

if (![String]::IsNullOrEmpty($category.name))
{
$xCategory.InnerText = $category.name.locale.GetAttribute("en-US")
}
$xProduct.AppendChild($xCategory)

break
}
}
break
}
}

# Find product variant
foreach ($productVariant in $productVariants.SelectNodes('productVariant'))
    {
if ($productVariant.productID -eq $productVariant.productID)
{
$xPrice = $xFeed.CreateElement('Price')
$xPrice.InnerText = $productVariant.basePrice
$xProduct.AppendChild($xPrice)

$xQuantity = $xFeed.CreateElement('Quantity')
$xQuantity.InnerText = $productVariant.inventory
$xProduct.AppendChild($xQuantity)

break
}
}

$xCondition = $xFeed.CreateElement('Condition')
$xCondition.InnerText = $Condition
$xProduct.AppendChild($xCondition)

$xLocation = $xFeed.CreateElement('Location')
$xLocation.InnerText = $Location
$xProduct.AppendChild($xLocation)

$xShippingOption = $xFeed.CreateElement('ShippingOption')
$xShippingOption.InnerText = $ShippingOption
$xProduct.AppendChild($xShippingOption)

# Get galleries
$productID = $product.productID
$xRequest = [Xml] "<?xml version='1.0' encoding='utf-8'?>
                       <request>
                         <version>1.0</version>
                         <credential>
                           <username>$APIUsername</username>
                           <apiKey>$APIKey</apiKey>
                         </credential>
                         <service>GetGalleriesByProduct</service>
                         <parameters>
  <productID>$productID</productID>
                         </parameters>
                       </request>"

   [Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
   if ($xResponse.response.code -ne '2000')
   {
       Throw New-Object System.InvalidOperationException("Error executing GetGalleriesByProduct. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
   }
   [System.Xml.XmlElement]$galleries = $xResponse.SelectSingleNode('/response/return/galleries')

# Find display gallery
$xImageURL = $xFeed.CreateElement('ImageURL')
foreach ($gallery in $galleries.SelectNodes('gallery'))
    {
if ($gallery.format -eq 2)
{
if (![String]::IsNullOrEmpty($gallery.mediaFile))
{
$xImageURL.InnerText = $SiteUrl + '/DesktopModules/Revindex.Dnn.RevindexStorefront/Portals/0/Gallery/' + $gallery.mediaFile.locale.GetAttribute("en-US")
}

break
}
}
$xProduct.AppendChild($xImageURL)

$xDescription = $xFeed.CreateElement('Description')

if (![String]::IsNullOrEmpty($product.overview))
{
$xDescription.InnerText = $product.overview.locale.GetAttribute("en-US") + " " + $product.summary.locale.GetAttribute("en-US")
}

if (![String]::IsNullOrEmpty($product.summary))
{
$xDescription.InnerText += " " + $product.summary.locale.GetAttribute("en-US")
}

$xProduct.AppendChild($xDescription)
    }

# Output file to disk
Out-File -FilePath ($WorkingFolder + $FeedFileName) -Encoding "UTF8" -InputObject $xFeed.InnerXml

    # Notify progress
    SendEmail $SMTPServer $SMTPUser $SMTPPassword $NotificationSender $NotificationRecipient 'Fulfillment completed successfully' 'Fulfillment completed successfully' ($WorkingFolder + $LogFileName)
}
Catch
{
    # Log errors
    ([DateTime]::Now.ToString("s") + "`t" + $_.Exception.Message + "`t") >> ($WorkingFolder + $LogFileName)
    
    # Notify error
    SendEmail $SMTPServer $SMTPUser $SMTPPassword $NotificationSender $NotificationRecipient 'Feed failed' 'Feed failed' ($WorkingFolder + $LogFileName)
}

Comments


Powered by Revindex Wiki