How to call AWS Cloudfront Update-CFDistribution Powershell Cmdlet - amazon-web-services

I have written the script to change the origin path" of a specific origin on a specific distribution in CloudFront. After changing the path I am getting errors when trying to update the distribution with the changes. I do not want to change anything else on the distribution besides the "origin path", so how do I call Update-CFDistribution to make these changes ideally without having to set every parameter (future updates to the API may cause this script to fail or even worst make incomplete modifications)?
$distributions = Get-CFDistributionList
foreach($distribution in $distributions) {
if($distribution.Id -eq "$CloudfrontDistributionId") {
foreach ($origin in $distribution.Origins) {
foreach($item in $origin.Items) {
if($item.Id -eq "OriginName") {
$item.OriginPath = "/$($S3BucketPrefix)"
Update-CFDistribution -Id $CloudfrontDistributionId -Origins_Item #($item)
}
}
}
}
}
Error
InvalidOperation: 5 validation errors detected: Value null at
'distributionConfig.defaultCacheBehavior' failed to satisfy
constraint: Member must not be null; Value null at
'distributionConfig.enabled' failed to satisfy constraint: Member must
not be null; Value null at 'distributionConfig.callerReference' failed
to satisfy constraint: Member must not be null; Value null at
'distributionConfig.origins.quantity' failed to satisfy constraint:
Member must not be null; Value at 'distributionConfig.comment' failed
to satisfy constraint: Member must not be null

I don't have the reputation to add just a comment so I'm having to put this as an answer, but it's better suited as a comment.
According to the documentation, there are a number of required fields when you issue an update, even if you're only trying to update one thing:
https://docs.aws.amazon.com/powershell/latest/reference/items/Update-CFDistribution.html
When you update a distribution, there are more required fields than
when you create a distribution. When you update your distribution by
using this API action, follow the steps here to get the current
configuration and then make your updates, to make sure that you
include all of the required fields.

I had the same issue and asked about it on the aws-tools-for-powershell Q&A. As far as I can tell, the answer is you just have to map all the properties. I took the time to do that today. In other PowerShell module contexts, I would expect you'd be able to just pipe in the object from a Get call with changes into an Update call and it would handle the parameter bindings. That doesn't work in this context. This is a known issue for a lot of aws-tools-for-powershell cmdlets according to aws-tools-for-powershell Issue #214.
Below is a snippet of the 66 mappings required to ensure you're updating all properties exactly as they were handed to you in the original Get call. It's possible fewer are actually required, but given I want an exact copy it felt safer to ensure all the data was available and let the API decide what could be dropped.
The etag thing is from: AWS PowerShell update CloudFront distribution
$distribution = Get-CFDistribution -Id $distributionFromList.Id
$etag = $AWSHistory.LastServiceResponse.ETag
$params = #{
Id = $distribution.Id
Verbose = $true
IfMatch = $etag
Aliases_Item = $distribution.DistributionConfig.Aliases.Items
Aliases_Quantity = $distribution.DistributionConfig.Aliases.Quantity
AllowedMethods_Item = $distribution.DistributionConfig.DefaultCacheBehavior.AllowedMethods.Items
AllowedMethods_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.AllowedMethods.Quantity
CacheBehaviors_Item = $distribution.DistributionConfig.CacheBehaviors.Items
CacheBehaviors_Quantity = $distribution.DistributionConfig.CacheBehaviors.Quantity
CachedMethods_Item = $distribution.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.Items
CachedMethods_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.Quantity
Cookies_Forward = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.Forward
CustomErrorResponses_Item = $distribution.DistributionConfig.CustomErrorResponses.Items
CustomErrorResponses_Quantity = $distribution.DistributionConfig.CustomErrorResponses.Quantity
DefaultCacheBehavior_CachePolicyId = $distribution.DistributionConfig.DefaultCacheBehavior.CachePolicyId
DefaultCacheBehavior_Compress = $distribution.DistributionConfig.DefaultCacheBehavior.Compress
DefaultCacheBehavior_DefaultTTL = $distribution.DistributionConfig.DefaultCacheBehavior.DefaultTTL
DefaultCacheBehavior_FieldLevelEncryptionId = $distribution.DistributionConfig.DefaultCacheBehavior.FieldLevelEncryptionId
DefaultCacheBehavior_MaxTTL = $distribution.DistributionConfig.DefaultCacheBehavior.MaxTTL
DefaultCacheBehavior_MinTTL = $distribution.DistributionConfig.DefaultCacheBehavior.MinTTL
DefaultCacheBehavior_OriginRequestPolicyId = $distribution.DistributionConfig.DefaultCacheBehavior.OriginRequestPolicyId
DefaultCacheBehavior_RealtimeLogConfigArn = $distribution.DistributionConfig.DefaultCacheBehavior.RealtimeLogConfigArn
DefaultCacheBehavior_ResponseHeadersPolicyId = $distribution.DistributionConfig.DefaultCacheBehavior.ResponseHeadersPolicyId
DefaultCacheBehavior_SmoothStreaming = $distribution.DistributionConfig.DefaultCacheBehavior.SmoothStreaming
DefaultCacheBehavior_TargetOriginId = $distribution.DistributionConfig.DefaultCacheBehavior.TargetOriginId
DefaultCacheBehavior_ViewerProtocolPolicy = $distribution.DistributionConfig.DefaultCacheBehavior.ViewerProtocolPolicy
DistributionConfig_CallerReference = $distribution.DistributionConfig.CallerReference
DistributionConfig_Comment = $distribution.DistributionConfig.Comment
DistributionConfig_DefaultRootObject = $distribution.DistributionConfig.DefaultRootObject
DistributionConfig_Enabled = $distribution.DistributionConfig.Enabled
DistributionConfig_HttpVersion = $distribution.DistributionConfig.HttpVersion
DistributionConfig_IsIPV6Enabled = $distribution.DistributionConfig.IsIPV6Enabled
DistributionConfig_PriceClass = $distribution.DistributionConfig.PriceClass
DistributionConfig_WebACLId = $distribution.DistributionConfig.WebACLId
ForwardedValues_QueryString = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryString
FunctionAssociations_Item = $distribution.DistributionConfig.DefaultCacheBehavior.FunctionAssociations.Items
FunctionAssociations_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.FunctionAssociations.Quantity
GeoRestriction_Item = $distribution.DistributionConfig.Restrictions.GeoRestriction.Items
GeoRestriction_Quantity = $distribution.DistributionConfig.Restrictions.GeoRestriction.Quantity
GeoRestriction_RestrictionType = $distribution.DistributionConfig.Restrictions.GeoRestriction.RestrictionType
Headers_Item = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.Items
Headers_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.Quantity
LambdaFunctionAssociations_Item = $distribution.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.Items
LambdaFunctionAssociations_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.Quantity
Logging_Bucket = $distribution.DistributionConfig.Logging.Bucket
Logging_Enabled = $distribution.DistributionConfig.Logging.Enabled
Logging_IncludeCookie = $distribution.DistributionConfig.Logging.IncludeCookies
Logging_Prefix = $distribution.DistributionConfig.Logging.Prefix
OriginGroups_Item = $distribution.DistributionConfig.OriginGroups.Items
OriginGroups_Quantity = $distribution.DistributionConfig.OriginGroups.Quantity
Origins_Item = $distribution.DistributionConfig.Origins.Items
Origins_Quantity = $distribution.DistributionConfig.Origins.Quantity
QueryStringCacheKeys_Item = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryStringCacheKeys.Items
QueryStringCacheKeys_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryStringCacheKeys.Quantity
TrustedKeyGroups_Enabled = $distribution.DistributionConfig.DefaultCacheBehavior.TrustedKeyGroups.Enabled
TrustedKeyGroups_Item = $distribution.DistributionConfig.DefaultCacheBehavior.TrustedKeyGroups.Items
TrustedKeyGroups_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.TrustedKeyGroups.Quantity
TrustedSigners_Enabled = $distribution.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Enabled
TrustedSigners_Item = $distribution.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Items
TrustedSigners_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Quantity
ViewerCertificate_ACMCertificateArn = $distribution.DistributionConfig.ViewerCertificate.ACMCertificateArn
ViewerCertificate_Certificate = $distribution.DistributionConfig.ViewerCertificate.Certificate
ViewerCertificate_CertificateSource = $distribution.DistributionConfig.ViewerCertificate.CertificateSource
ViewerCertificate_CloudFrontDefaultCertificate = $distribution.DistributionConfig.ViewerCertificate.CloudFrontDefaultCertificate
ViewerCertificate_IAMCertificateId = $distribution.DistributionConfig.ViewerCertificate.IAMCertificateId
ViewerCertificate_MinimumProtocolVersion = $distribution.DistributionConfig.ViewerCertificate.MinimumProtocolVersion
ViewerCertificate_SSLSupportMethod = $distribution.DistributionConfig.ViewerCertificate.SSLSupportMethod
WhitelistedNames_Item = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.Items
WhitelistedNames_Quantity = $distribution.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.Quantity
}
Update-CFDistribution #params -WhatIf

Related

How exactly is tensorflow.control_dependecy applied?

self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
with tf.control_dependencies([optimizer_op]):
self.optimizer = control_ops
i call self.optimizer with the session
The code above is not updating the gradients. However if i change the control dependencies part of the code to the one below it works perfectly fine except that it misses out on a final exponential moving average (self.ema_op) update, which is not desirable to me:
self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
# with tf.control_dependencies(optimizer_op):
# self.optimizer = control_ops
with tf.control_dependencies([self.ema_op] + update_ops_):
self.optimizer = optimizer.apply_gradients(zip(clipped_gradients, variables))
Please tell me what am i missing?
You need to define the tensorflow operations under the with statement, not just set the variable. Doing self.optimizer = control_ops has no effect because you did not create any tensorflow operations.
Without fully understanding your problem I think you want something like this:
with tf.control_dependencies(optimizer_op):
control_ops = tf.group([self.ema_op] + update_ops_)
self.optimizer = control_ops
The with statement enters a block, under which any new ops you create in tensorflow will be dependent upon optimizer_op in this case.

Dynamics GP Web Services: Changing policy behavior at runtime

I am creating a payables invoices using Web Services on GP2013. Optionally, my users can provide line item distributions. I can create invoices, but unless I modify the CreatePayablesInvoice policy to "Distributions Will Be Provided" in the dynamics security console, the invoice gets both the system provided distributions as well as the distribution lines I am creating. I want to have the ability to provide distributions if necessary, otherwise I want the system to handle it.
The documentation suggests I should be able to alter the policy in code, but when I get the policy object back from GetPolicyByOperation, the Behaviors array is empty. I have tried creating the behavior manually in code and it doesn't alter what happens when the invoice is created. The only thing that impacts the result is editing the property in the security console.
My code for altering the the policy is below:
payablesInvoiceCreatePolicy = wsDynamicsGP.GetPolicyByOperation("CreatePayablesInvoice", context);
BehaviorKey bk = new BehaviorKey();
bk.Id = new Guid("e476a157-ecf0-4dae-8cef-317dd2cfbe41");
Behavior b = new Behavior();
b.Key = bk;
BehaviorOption opt0 = new BehaviorOption();
opt0.Key = new BehaviorOptionKey();
opt0.Key.Id = 0;
opt0.Name = "Distributions Will Be Provided";
BehaviorOption opt1 = new BehaviorOption();
opt1.Key = new BehaviorOptionKey();
opt1.Key.Id = 1;
opt1.Name = "Automatically Create Distributions";
b.Options = new BehaviorOption[] { opt0, opt1 };
b.SelectedOption = b.Options[1];
payablesInvoiceCreatePolicy.Behaviors = new Behavior[]{b};
wsDynamicsGP.CreatePayablesInvoice(payablesInvoice, context, payablesInvoiceCreatePolicy);
Documentation seems to be sparse on what should or shouldn't work here. I have to assume I should be able to update the policy as I see fit at runtime based on whether or not my user has decided to provide line item distributions.
Does anyone know what I am missing?
Yes. It took me 2 days to fix this myself. After adding the behaviour to the policy object UpdatePolicy before calling the create invoice as below:
wsDynamicsGP.UpdatePolicy(payablesInvoiceCreatePolicy, new RoleKey { Id = "00000000-0000-0000-0000-000000000000" }, context)
wsDynamicsGP.CreatePayablesInvoice(payablesInvoice, context, payablesInvoiceCreatePolicy);
Note that you selected the behavior that automatically creates distribution lines on invoice creation. The behavior's Internal property also must be set to true.
Here is a working example also utilizing FlowerKing's answer:
BehaviorKey bk = new BehaviorKey();
bk.Id = new Guid("e476a157-ecf0-4dae-8cef-317dd2cfbe41");
bk.PolicyKey = payablesInvoiceCreatePolicy.Key;
Behavior b = new Behavior();
b.Key = bk;
b.Internal = true;
BehaviorOption opt0 = new BehaviorOption();
opt0.Key = new BehaviorOptionKey();
opt0.Key.Id = 0;
opt0.Name = "Distributions Will Be Provided";
BehaviorOption opt1 = new BehaviorOption();
opt1.Key = new BehaviorOptionKey();
opt1.Key.Id = 1;
opt1.Name = "Automatically Create Distributions";
b.Options = new BehaviorOption[] { opt0, opt1 };
b.SelectedOption = b.Options[0];
policy.Behaviors = new Behavior[] { b };
client.UpdatePolicy(payablesInvoiceCreatePolicy, new RoleKey { Id = "00000000-0000-0000-0000-000000000000" }, context);
client.CreatePayablesInvoice(payablesInvoice, context, payablesInvoiceCreatePolicy);

Codeigniter routing how to permit null parameter

I want paginate my index http:localhost/mysite/home but if I write only this http:localhost/mysite/home the page said: "page not found", but if I write http:localhost/mysite/home/3 its work! how to I can configure my routing to get null parameters? I tried with (:any) and (num) but not work
My route file is:
$route['404_override'] = 'welcome/no_found';
$route['home/'] = "welcome/home/$1";
My controller:
$config['base_url'] = base_url().'/mysite/home';
$config['total_rows'] = $this->mtestmodel->countNews();
$config['per_page'] = 2;
$config['num_links'] = 20;
$this->pagination->initialize($config);
$data['paginator']=$this->pagination->create_links();
$data['news']=$this->mtestmodel->show_news( $config['per_page'],intval($to) );
//$to is a parameter in url base_url()/mysite/home/3
Change your route.php file to the following:
$route['404_override'] = 'welcome/no_found';
$route['home/(:num)'] = "welcome/home/$1";
$route['home'] = "welcome/home";
This way, your application will catch both requests (http://localhost/mysite/home and http://localhost/mysite/home/3), and will send them both to your controller.
You should then be able to access your $to variable (which has been passed as the first argument into your controller's function) or use $this->uri->segment(2) instead.
e.g.
public function home($to = 0) {
$config['base_url'] = base_url().'/mysite/home';
$config['total_rows'] = $this->mtestmodel->countNews();
$config['per_page'] = 2;
$config['num_links'] = 20;
$this->pagination->initialize($config);
$data['paginator'] = $this->pagination->create_links();
$data['news'] = $this->mtestmodel->show_news( $config['per_page'],intval($to) );
}
Hope that helps!

Dynamics GP Web Services: SalesInvoice Creation with Lot Allocation

I'm trying to use the following code to create a new SalesInvoice based on an existing SalesOrder:
SalesInvoice invoice = new SalesInvoice();
invoice.DocumentTypeKey = new SalesDocumentTypeKey { Type = SalesDocumentType.Invoice };
invoice.CustomerKey = originalOrder.CustomerKey;
invoice.BatchKey = originalOrder.BatchKey;
invoice.Terms = new SalesTerms { DiscountTakenAmount = new MoneyAmount { Value = 0, Currency = "USD", DecimalDigits = 2 }, DiscountAvailableAmount = new MoneyAmount { Value = 0, Currency = "USD", DecimalDigits = 0 } };
invoice.OriginalSalesDocumentKey = originalOrder.Key;
List<SalesInvoiceLine> lineList = new List<SalesInvoiceLine>();
for (int i = 0; i < originalOrder.Lines.Length; i++)
{
SalesInvoiceLine line = new SalesInvoiceLine();
line.ItemKey = originalOrder.Lines[i].ItemKey;
line.Key = new SalesLineKey { LineSequenceNumber = originalOrder.Lines[i].Key.LineSequenceNumber; }
SalesLineLot lot = new SalesLineLot();
lot.LotNumber = originalOrder.Lines[i].Lots[0].LotNumber;
lot.Quantity = new Quantity { Value = 2200 };
lot.Key = new SalesLineLotKey { SequenceNumber = originalOrder.Lines[i].Lots[0].Key.SequenceNumber };
line.Lots = new SalesLineLot[] { lot };
line.Quantity = new Quantity { Value = 2200 };
lineList.Add(line);
}
invoice.Lines = lineList.ToArray();
DynamicsWS.CreateSalesInvoice(invoice, DynamicsContext, DynamicsWS.GetPolicyByOperation("CreateSalesInvoice", DynamicsContext));
When executed, I receive the following error:
SQL Server Exception: Operation expects a parameter which was not supplied.
And the more detailed exception from the Exception Console in Dynamics:
Procedure or function 'taSopLotAuto' expects parameter '#I_vLNITMSEQ',
which was not supplied.
After a considerable amount of digging through Google, I discovered a few things.
'taSopLotAuto' is an eConnect procedure within the Sales Order Processing component that attempts to automatically fill lots. I do not want the lots automatically filled, which is why I try to fill them manually in the code. I've also modified the CreateSalesInvoice policy from Automatic lot fulfillment to Manual lot fulfillment for the GP web services user, but that didn't change which eConnect procedure was called.
'#I_vLNITMSEQ' refers to the LineSequenceNumber. The LineSequenceNumber and SequenceNumber (of the Lot itself) must match. In my case they are both the default: 16384. Not only is this parameter set in the code above, but it also appears in the SOAP message that the server attempted to process - hardly "not supplied."
I can create an invoice sans line items without a hitch, but if I add line items it fails. I do not understand why I am receiving an error for a missing parameter that is clearly present.
Any ideas on how to successfully create a SalesInvoice through Dynamics GP 10.0 Web Services?
Maybe you mess to add the line key to the lot:
lot.Key = new SalesLineKey();
lot.Key.SalesDocumentKey = new SalesDocumentKey();
lot.Key.SalesDocumentKey.Id = seq.ToString();

Subsonic 3 Save() then Update()?

I need to get the primary key for a row and then insert it into one of the other columns in a string.
So I've tried to do it something like this:
newsObj = new news();
newsObj.name = "test"
newsObj.Save();
newsObj.url = String.Format("blah.aspx?p={0}",newsObj.col_id);
newsObj.Save();
But it doesn't treat it as the same data object so newsObj.col_id always comes back as a zero. Is there another way of doing this? I tried this on another page and to get it to work I had to set newsObj.SetIsLoaded(true);
This is the actual block of code:
page p;
if (pageId > 0)
p = new page(ps => ps.page_id == pageId);
else
p = new page();
if (publish)
p.page_published = 1;
if (User.IsInRole("administrator"))
p.page_approved = 1;
p.page_section = staticParent.page_section;
p.page_name = PageName.Text;
p.page_parent = parentPageId;
p.page_last_modified_date = DateTime.Now;
p.page_last_modified_by = (Guid)Membership.GetUser().ProviderUserKey;
p.Add();
string urlString = String.Empty;
if (parentPageId > 0)
{
urlString = Regex.Replace(staticParent.page_url, "(.aspx).*$", "$1"); // We just want the static page URL (blah.aspx)
p.page_url = String.Format("{0}?p={1}", urlString, p.page_id);
}
p.Save();
If I hover the p.Save(); I can see the correct values in the object but the DB is never updated and there is no exception.
Thanks!
I faced the same problem with that :
po oPo = new po();
oPo.name ="test";
oPo.save(); //till now it works.
oPo.name = "test2";
oPo.save(); //not really working, it's not saving the data since isLoaded is set to false
and the columns are not considered dirty.
it's a bug in the ActiveRecord.tt for version 3.0.0.3.
In the method public void Add(IDataProvider provider)
immediately after SetIsNew(false);
there should be : SetIsLoaded(true);
the reason why the save is not working the second time is because the object can't get dirty if it is not loaded. By adding the SetIsLoaded(true) in the ActiveRecord.tt, when you are going to do run custom tool, it's gonna regenerate the .cs perfectly.