text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol Chainable {
//Chainable methods
func then() -> UIView
func animate() -> Void
}
//CALayer
public protocol Chainable1 {
//Chainable methods
func then() -> CALayer
func animate() -> Void
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/Chainable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 260 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
extension Float: Physical {
//Vetorial
public func convert(_ p: Vector4) -> Float {
return Float(p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.two = Double(self)
return vector
}
//Interpolatable
public func interpolate(_ progress: Double, to: Float, externalData: Any?) -> Float {
let change = to - self
return self + change * Float(progress)
}
}
extension Double: Physical {
//Vetorial
public func convert(_ p: Vector4) -> Double {
return p.two
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.two = self
return vector
}
//Interpolatable
public func interpolate(_ progress: Double, to: Double, externalData: Any?) -> Double {
let change = to - self
return self + change * progress
}
}
extension CGFloat: Physical {
public func convert(_ p: Vector4) -> CGFloat {
return CGFloat(p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.two = Double(self)
return vector
}
//Interpolatable
public func interpolate(_ progress: Double, to: CGFloat, externalData: Any?) -> CGFloat {
let change = to - self
return self + change * CGFloat(progress)
}
}
extension CGSize: Physical {
//
public func convert(_ p: Vector4) -> CGSize {
return CGSize(width: p.one, height: p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.one = Double(self.width)
vector.two = Double(self.height)
return vector
}
//
public func interpolate(_ progress: Double, to: CGSize, externalData: Any?) -> CGSize {
let wChnaged = to.width - self.width;
let hChanged = to.height - self.height;
let currentW = self.width + wChnaged * CGFloat(progress);
let currentH = self.height + hChanged * CGFloat(progress);
return CGSize(width: currentW, height: currentH)
}
}
extension CGPoint: Physical {
//
public func convert(_ p: Vector4) -> CGPoint {
return CGPoint(x: p.one, y: p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.one = Double(self.x)
vector.two = Double(self.y)
return vector
}
public func interpolate(_ progress: Double, to: CGPoint, externalData: Any?) -> CGPoint {
let xChnaged = to.x - self.x;
let yChanged = to.y - self.y;
let currentX = self.x + xChnaged * CGFloat(progress);
let currentY = self.y + yChanged * CGFloat(progress);
return CGPoint(x: currentX, y: currentY)
}
}
extension CGRect: Physical {
public func convert(_ p: Vector4) -> CGRect {
return CGRect.init(x: p.one, y: p.two, width: p.three, height: p.four)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.one = Double(self.origin.x)
vector.two = Double(self.origin.y)
vector.three = Double(self.size.width)
vector.four = Double(self.size.height)
return vector
}
//
public func interpolate(_ progress: Double, to: CGRect, externalData: Any?) -> CGRect {
let xChanged = to.minX - self.minX
let yChanged = to.minY - self.minY
let wChnaged = to.width - self.width;
let hChanged = to.height - self.height;
let currentX = self.minX + xChanged * CGFloat(progress)
let currentY = self.minY + yChanged * CGFloat(progress)
let currentW = self.width + wChnaged * CGFloat(progress)
let currentH = self.height + hChanged * CGFloat(progress)
return CGRect(x: currentX, y: currentY, width: currentW, height: currentH)
}
}
extension UIColor: Physical {
//
public func convert(_ p: Vector4) -> Self {
let hue = p.one / 250.0
let saturation = p.two / 250.0
let brightness = p.three / 250.0
let alpha = p.four / 250.0
return convertT(CGFloat(hue),saturation: CGFloat(saturation),brightness: CGFloat(brightness),alpha: CGFloat(alpha))
}
public func reverse() -> Vector4 {
var hue: CGFloat = 0.0
var saturation: CGFloat = 0.0
var brightness: CGFloat = 0.0
var alpha: CGFloat = 0.0
self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
hue *= 250.0
saturation *= 250.0
brightness *= 250.0
alpha *= 250.0
let vector = Vector4()
vector.one = Double(hue)
vector.two = Double(saturation)
vector.three = Double(brightness)
vector.four = Double(alpha)
return vector
}
fileprivate func convertT<T>(_ hue: CGFloat,saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) -> T {
let color = UIColor(hue: hue,saturation: saturation,brightness: brightness,alpha: alpha)
return unsafeBitCast(color, to: T.self)
}
//
public func interpolate(_ progress: Double, to: UIColor, externalData: Any?) -> Self {
let infos = externalData as! (ColorInfo,ColorInfo)
let fromInfo = infos.0
let toInfo = infos.1
let changedHue = toInfo.hue - fromInfo.hue
let changedSaturation = toInfo.saturation - fromInfo.saturation
let changedBrightness = toInfo.brightness - fromInfo.brightness
let changedAlpha = toInfo.alpha - fromInfo.alpha
let curHue = fromInfo.hue + changedHue * CGFloat(progress)
let curSaturation = fromInfo.saturation + changedSaturation * CGFloat(progress)
let curBrightness = fromInfo.brightness + changedBrightness * CGFloat(progress)
let curAlpha = fromInfo.alpha + changedAlpha * CGFloat(progress)
return convertT(curHue,saturation: curSaturation,brightness: curBrightness,alpha: curAlpha)
}
//performance
typealias ColorInfo = (hue:CGFloat,saturation:CGFloat,brightness:CGFloat,alpha:CGFloat)
internal func colorInfo() -> ColorInfo {
var hue: CGFloat = 0.0
var saturation: CGFloat = 0.0
var brightness: CGFloat = 0.0
var alpha: CGFloat = 0.0
self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return (hue,saturation,brightness,alpha)
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/Value+Physical.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,783 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
extension UITextView {
// public func makeTextColor(color: UIColor) -> UIView {
// let type = AnimationType(type: .Basic, subType: .TextColor(color))
// context.addAnimationType(type)
// return self
// }
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/UITextView+Stellar.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 255 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
//for 4 latitude
final class DynamicItem<T: Vectorial>: NSObject, UIDynamicItem {
var from: T
var to: T
var render: (T) -> Void
var complete = false
var boundaryLimit = false
var completion: (() -> Void)?
internal var fromR: Vector4
internal var toR: Vector4
weak var behavior: UIDynamicBehavior!
fileprivate var change: (x: Double,y: Double,z: Double,w: Double)
var referenceChangeLength: Double
init(from: T, to: T, render: @escaping (T) -> Void) {
self.from = from
self.to = to
self.render = render
//
self.fromR = from.reverse()
self.toR = to.reverse()
//
let x = toR.one - fromR.one
let y = toR.two - fromR.two
let z = toR.three - fromR.three
let w = toR.four - fromR.four
self.change = (x,y,z,w)
//
let originChange = sqrt(x*x + y*y)
let sizeChange = sqrt(z*z + w*w)
self.referenceChangeLength = max(originChange, sizeChange)
}
deinit {
self.render(to)
complete = true
completion?()
}
//MARK: Update frame
func updateFrame() {
let yChange = fabs(Double(center.y))
let progress = yChange / referenceChangeLength
let curX = fromR.one + change.x * progress;
let curY = fromR.two + change.y * progress;
let curZ = fromR.three + change.z * progress;
let curW = fromR.four + change.w * progress;
let rect = Vector4.init((curX,curY,curZ,curW))
var curV = from.convert(rect)
if progress >= 1.0 {
if boundaryLimit {
curV = to
behavior.cancel()
complete = true
}
}
self.render(curV)
}
//MARK: UIDynamicItem protocol
var center: CGPoint = CGPoint.zero {
didSet {
updateFrame()
}
}
var transform: CGAffineTransform = CGAffineTransform.identity
var bounds: CGRect {
get {
return CGRect(x: -50.0, y: -50.0, width: 100.0, height: 100.0)
}
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/DynamicItem.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 753 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
internal class AnimationStep {
var types = [AnimationType]()
var duration: CFTimeInterval = 0.25
var timing: TimingFunctionType = .default
var delay: CFTimeInterval = 0.0
var autoreverses: Bool = false
var repeatCount: Int = 0
var completion: (() -> Void)?
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/AnimationStep.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 280 |
```swift
//
// CALayer+AnimateBehavior.swift
// StellarDemo
//
// Created by AugustRush on 6/21/16.
//
import UIKit
extension CALayer: DriveAnimateBehaviors {
func behavior(forType type: AnimationType, step: AnimationStep) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
let mainType = type.mainType
let subType = type.subType
switch mainType {
case .basic:
behavior = createBasicAnimationWithType(subType, step: step)
case .snap(let d):
behavior = createSnapAnimationWithType(subType, damping: d)
case .attachment(let damping, let frequency):
behavior = createAttachmentAnimationWithType(subType, damping: damping, frequency: frequency)
case .gravity(let magnitude):
behavior = createGravityAnimationWithType(subType, magnitude: magnitude)
}
return behavior
}
//MARK: Basic
fileprivate func createBasicAnimationWithType(_ type: AnimationSubType, step: AnimationStep) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveTo(let position):
let from = self.position
let to = position
let render = {(p: CGPoint) in
self.position = p
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .moveXY(let x, let y):
let from = CGPoint.zero
let to = CGPoint(x: x, y: y)
let frame = self.frame
let render = {(p: CGPoint) in
self.frame = frame.offsetBy(dx: p.x, dy: p.y)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .color(let color):
var from = UIColor.clear
if let bc = self.backgroundColor {
from = UIColor(cgColor: bc)
}
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c.cgColor
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .opacity(let o):
let from = self.opacity
let to = o
let render = {(f: Float) in
self.opacity = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .width(let w):
let from = self.bounds.width
let to = w
let render = {(f: CGFloat) in
self.bounds.size.width = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.transform
let render = {(p: CGPoint) in
self.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.cornerRadius = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.borderWidth
let to = b
let render = {(f: CGFloat) in
self.borderWidth = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.shadowRadius = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.zPosition
let to = p
let render = {(f: CGFloat) in
self.zPosition = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.anchorPoint = p
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.anchorPointZ = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.shadowOffset
let to = size
let render = {(s: CGSize) in
self.shadowOffset = s
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.shadowColor = c.cgColor
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.shadowOpacity
let to = o
let render = {(f: Float) in
self.shadowOpacity = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
default:
fatalError("Should not be excute forever!")
}
return behavior
}
//MARK: Snap
fileprivate func createSnapAnimationWithType(_ type: AnimationSubType, damping: CGFloat) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveTo(let position):
let from = self.position
let to = position
let render = {(p: CGPoint) in
self.position = p
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .moveXY(let x, let y):
let from = CGPoint.zero
let to = CGPoint(x: x, y: y)
let frame = self.frame
let render = {(p: CGPoint) in
self.frame = frame.offsetBy(dx: p.x, dy: p.y)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .color(let color):
var from = UIColor.clear
if let bc = self.backgroundColor {
from = UIColor(cgColor: bc)
}
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c.cgColor
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .opacity(let o):
let from = self.opacity
let to = o
let render = {(f: Float) in
self.opacity = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .width(let w):
let from = self.bounds.width
let to = w
let render = {(f: CGFloat) in
self.bounds.size.width = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.transform
let render = {(p: CGPoint) in
self.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.cornerRadius = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.borderWidth
let to = b
let render = {(f: CGFloat) in
self.borderWidth = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.shadowRadius = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.zPosition
let to = p
let render = {(f: CGFloat) in
self.zPosition = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.anchorPoint = p
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.anchorPointZ = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.shadowOffset
let to = size
let render = {(s: CGSize) in
self.shadowOffset = s
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.shadowColor = c.cgColor
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.shadowOpacity
let to = o
let render = {(f: Float) in
self.shadowOpacity = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
default:
fatalError("Should not be excute forever!")
}
return behavior
}
//MARK: Attachment
fileprivate func createAttachmentAnimationWithType(_ type: AnimationSubType, damping: CGFloat, frequency: CGFloat) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveTo(let position):
let from = self.position
let to = position
let render = {(p: CGPoint) in
self.position = p
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .moveXY(let x, let y):
let from = CGPoint.zero
let to = CGPoint(x: x, y: y)
let frame = self.frame
let render = {(p: CGPoint) in
self.frame = frame.offsetBy(dx: p.x, dy: p.y)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .color(let color):
var from = UIColor.clear
if let bc = self.backgroundColor {
from = UIColor(cgColor: bc)
}
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c.cgColor
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .opacity(let o):
let from = self.opacity
let to = o
let render = {(f: Float) in
self.opacity = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .width(let w):
let from = self.bounds.width
let to = w
let render = {(f: CGFloat) in
self.bounds.size.width = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.transform
let render = {(p: CGPoint) in
self.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.cornerRadius = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.borderWidth
let to = b
let render = {(f: CGFloat) in
self.borderWidth = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.shadowRadius = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.zPosition
let to = p
let render = {(f: CGFloat) in
self.zPosition = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.anchorPoint = p
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.anchorPointZ = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.shadowOffset
let to = size
let render = {(s: CGSize) in
self.shadowOffset = s
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.shadowColor = c.cgColor
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.shadowOpacity
let to = o
let render = {(f: Float) in
self.shadowOpacity = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
default:
fatalError("Should not be excute forever!")
}
return behavior
}
//MARK: Gravity
fileprivate func createGravityAnimationWithType(_ type: AnimationSubType, magnitude: Double) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveTo(let position):
let from = self.position
let to = position
let render = {(p: CGPoint) in
self.position = p
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .moveXY(let x, let y):
let from = CGPoint.zero
let to = CGPoint(x: x, y: y)
let frame = self.frame
let render = {(p: CGPoint) in
self.frame = frame.offsetBy(dx: p.x, dy: p.y)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .color(let color):
var from = UIColor.clear
if let bc = self.backgroundColor {
from = UIColor(cgColor: bc)
}
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c.cgColor
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .opacity(let o):
let from = self.opacity
let to = o
let render = {(f: Float) in
self.opacity = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .width(let w):
let from = self.bounds.width
let to = w
let render = {(f: CGFloat) in
self.bounds.size.width = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.transform
let render = {(p: CGPoint) in
self.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.cornerRadius = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.borderWidth
let to = b
let render = {(f: CGFloat) in
self.borderWidth = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.shadowRadius = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.zPosition
let to = p
let render = {(f: CGFloat) in
self.zPosition = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.anchorPoint = p
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.anchorPointZ = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.shadowOffset
let to = size
let render = {(s: CGSize) in
self.shadowOffset = s
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.shadowColor = c.cgColor
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.shadowOpacity
let to = o
let render = {(f: Float) in
self.shadowOpacity = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
default:
fatalError("Should not be excute forever!")
// case .TextColor(let color):
// let fromColor = self.performSelector(Selector("textColor")).takeUnretainedValue() as? UIColor
// let from = fromColor ?? UIColor.clearColor()
// let to = color
// let render = { (cc: UIColor) in
// self.performSelector(Selector("setTextColor:"),withObject: cc)
// }
// behavior = basicBehavior(step, from: from, to: to, render: render)
}
return behavior
}
//MARK: Private methods
fileprivate func basicBehavior<T: Interpolatable>(_ step: AnimationStep,from: T, to: T, render: @escaping ((T) -> Void)) -> UIDynamicBehavior {
let item = DynamicItemBasic(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.duration = step.duration
item.timingFunction = step.timing.easing()
item.delay = step.delay
item.repeatCount = step.repeatCount
item.autoreverses = step.autoreverses
return push
}
fileprivate func snapBehavior<T: Vectorial>(_ damping: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let snap = item.snapBehavior(point, damping: damping)
item.behavior = snap
return snap
}
fileprivate func attachmentBehavior<T: Vectorial>(_ damping: CGFloat, frequency: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let attachment = item.attachmentBehavior(point, length: 0.0, damping: damping, frequency: frequency)
item.behavior = attachment
return attachment
}
fileprivate func gravityBehavior<T: Interpolatable>(_ magnitude: Double, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItemGravity(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.magnitude = magnitude
return push
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/CALayer+AnimateBehavior.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 8,356 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol BasicChainable: Chainable {
func moveX(_ increment: CGFloat) -> UIView
func moveY(_ increment: CGFloat) -> UIView
func moveTo(_ point: CGPoint) -> UIView
func makeColor(_ color: UIColor) -> UIView
func makeAlpha(_ alpha: CGFloat) -> UIView
func rotate(_ z: CGFloat) -> UIView
func rotateX(_ x: CGFloat) -> UIView
func rotateY(_ y: CGFloat) -> UIView
func rotateXY(_ xy: CGFloat) -> UIView
func makeWidth(_ width: CGFloat) -> UIView
func makeHeight(_ height: CGFloat) -> UIView
func makeSize(_ size: CGSize) -> UIView
func makeFrame(_ frame: CGRect) -> UIView
func makeBounds(_ bounds: CGRect) -> UIView
func scaleX(_ x: CGFloat) -> UIView
func scaleY(_ y: CGFloat) -> UIView
func scaleXY(_ x: CGFloat, _ y: CGFloat) -> UIView
func cornerRadius(_ radius: CGFloat) -> UIView
func borderWidth(_ width: CGFloat) -> UIView
func shadowRadius(_ radius: CGFloat) -> UIView
func zPosition(_ position: CGFloat) -> UIView
func anchorPoint(_ point: CGPoint) -> UIView
func anchorPointZ(_ z: CGFloat) -> UIView
func shadowOffset(_ offset: CGSize) -> UIView
func shadowColor(_ color: UIColor) -> UIView
func shadowOpacity(_ opacity: Float) -> UIView
func makeTintColor(_ color: UIColor) -> UIView
func completion(_ c: @escaping () -> Void) -> UIView
}
//CALayer
public protocol BasicChainable1: Chainable1 {
func moveTo(_ point: CGPoint) -> CALayer
func makeColor(_ color: UIColor) -> CALayer
func makeOpacity(_ opacity: Float) -> CALayer
func rotate(_ z: CGFloat) -> CALayer
func rotateX(_ x: CGFloat) -> CALayer
func rotateY(_ y: CGFloat) -> CALayer
func rotateXY(_ xy: CGFloat) -> CALayer
func makeWidth(_ width: CGFloat) -> CALayer
func makeHeight(_ height: CGFloat) -> CALayer
func makeSize(_ size: CGSize) -> CALayer
func makeFrame(_ frame: CGRect) -> CALayer
func makeBounds(_ bounds: CGRect) -> CALayer
func scaleX(_ x: CGFloat) -> CALayer
func scaleY(_ y: CGFloat) -> CALayer
func scaleXY(_ x: CGFloat, _ y: CGFloat) -> CALayer
func cornerRadius(_ radius: CGFloat) -> CALayer
func borderWidth(_ width: CGFloat) -> CALayer
func shadowRadius(_ radius: CGFloat) -> CALayer
func zPosition(_ position: CGFloat) -> CALayer
func anchorPoint(_ point: CGPoint) -> CALayer
func anchorPointZ(_ z: CGFloat) -> CALayer
func shadowOffset(_ offset: CGSize) -> CALayer
func shadowColor(_ color: UIColor) -> CALayer
func shadowOpacity(_ opacity: Float) -> CALayer
func completion(_ c: @escaping () -> Void) -> CALayer
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/BasicChainable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 897 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
internal class AnimationContext: NSObject, UIDynamicAnimatorDelegate, AnimationSequenceDelegate {
fileprivate weak var object: DriveAnimateBehaviors!
fileprivate var mutipleSequences = [AnimationSequence]()
//MARK: init method
init(object: DriveAnimateBehaviors) {
self.object = object
}
//MARK: public methods
func addAnimationType(_ type: AnimationType) {
let step = lastStep()
step.types.append(type)
}
func changeDuration(_ d: CFTimeInterval) {
let step = lastStep()
step.duration = d
}
func changeDelay(_ d: CFTimeInterval) {
let step = lastStep()
step.delay = d
}
func changeAutoreverses(_ a: Bool) {
let step = lastStep()
step.autoreverses = a
}
func changeRepeatCount(_ count: Int) {
let step = lastStep()
step.repeatCount = count
}
func changeCompletion(_ c: @escaping () -> Void) {
let step = lastStep()
step.completion = c
}
func changeEasing(_ e: TimingFunctionType) {
let step = lastStep()
step.timing = e
}
func changeMainType(_ type: AnimationStyle) {
let step = lastStep()
let lastAnimationType = step.types.last
guard let _ = lastAnimationType else {
print("You should defined animaton first!")
return
}
lastAnimationType!.mainType = type
}
func makeNextStep() {
let step = AnimationStep()
lastSequence().addStep(step)
}
@discardableResult
func makeNextSequence() -> AnimationSequence {
let sequence = AnimationSequence(object: self.object)
sequence.delegate = self
mutipleSequences.append(sequence)
return sequence
}
func commit() {
//start all sequence
for sequence in mutipleSequences {
sequence.start()
}
//make a temple sequence for next step
makeNextSequence()
}
func removeAllRemaining() {
for sequence in mutipleSequences {
sequence.removeAllSteps()
}
mutipleSequences.removeAll()
}
//MARK: private methods
fileprivate func lastSequence() -> AnimationSequence {
var sequence = mutipleSequences.last
if sequence == nil {
sequence = makeNextSequence()
}
return sequence!
}
fileprivate func lastStep() -> AnimationStep {
let sequence = lastSequence()
var step = sequence.last()
if step == nil {
step = AnimationStep()
sequence.addStep(step!)
}
return step!
}
//MARK: AnimationSequenceDelegate methods
func animationSequenceDidComplete(_ sequence: AnimationSequence) {
let index = mutipleSequences.index(of: sequence)
if index != nil {
mutipleSequences.remove(at: index!)
}
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/AnimationContext.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 851 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
public protocol Interpolatable: Vectorial {
func interpolate(_ progress: Double, to: Self, externalData: Any?) -> Self
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/Interpolatable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 232 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
class DynamicItemGravity<T: Interpolatable>: NSObject, UIDynamicItem {
var from: T!
var to: T!
var magnitude = 1.0
var render: (T) -> Void
var completion: (() -> Void)?
var boundary = true
weak var behavior: UIDynamicBehavior?
//private vars
fileprivate var referenceChangedLength: Double = 0.0
//External data to store (performance)
fileprivate var externalData: Any?
fileprivate lazy var beginTime = {
return CACurrentMediaTime()
}()
//MARK: init method
init(from: T, to: T, render: @escaping (T) -> Void) {
self.from = from
self.to = to
self.render = render
super.init()
caculateReferenceChangedLength()
}
deinit {
self.completion?()
}
//MARK: private methods
fileprivate func caculateReferenceChangedLength() {
switch from {
case let f as CGFloat:
let t = to as! CGFloat
referenceChangedLength = Double(fabs(t - f))
case let f as Float:
let t = to as! Float
referenceChangedLength = Double(fabs(t - f))
case let f as Double:
let t = to as! Double
referenceChangedLength = fabs(t - f)
case let f as CGSize:
let t = to as! CGSize
let w = fabs(t.width - f.width)
let h = fabs(t.height - f.height)
referenceChangedLength = max(Double(w), Double(h))
case let f as CGPoint:
let t = to as! CGPoint
let x = fabs(t.x - f.x)
let y = fabs(t.y - f.y)
referenceChangedLength = max(Double(x), Double(y))
case let f as CGRect:
let t = to as! CGRect
let xChange = fabs(t.minX - f.minX)
let yChange = fabs(t.minY - f.minY)
let wChange = fabs(t.width - f.width)
let hChange = fabs(t.height - f.height)
let originC = hypot(xChange, yChange)
let sizeC = hypot(wChange, hChange)
referenceChangedLength = max(Double(originC), Double(sizeC))
case let f as UIColor:
let t = to as! UIColor
let fromInfo = f.colorInfo()
let toInfo = t.colorInfo()
let hueChange = fabs(toInfo.hue - fromInfo.hue)
let brightnessChange = fabs(toInfo.brightness - fromInfo.brightness)
let saturationChange = fabs(toInfo.saturation - fromInfo.saturation)
let alphaChange = fabs(toInfo.alpha - fromInfo.alpha)
let oneC = hypot(hueChange, saturationChange) * 1000.0
let twoC = hypot(brightnessChange, alphaChange) * 1000.0
referenceChangedLength = max(Double(oneC), Double(twoC))
externalData = (fromInfo,toInfo)
default:
referenceChangedLength = 1000.0
}
}
fileprivate func updateFrame() {
if referenceChangedLength <= 0.0 {
behavior?.cancel()
return
}
var currentTime = CACurrentMediaTime() - beginTime
currentTime = max(0.0, currentTime)
let offset = gravityOffset(currentTime)
var progress = offset / referenceChangedLength
if progress >= 1.0 {
if boundary {
progress = 1.0
behavior?.cancel()
}
}
let value = from.interpolate(progress, to: to, externalData: externalData)
render(value)
}
fileprivate func gravityOffset(_ t: CFTimeInterval) -> Double {
return t * t * 1000.0 * magnitude;
}
//MARK: UIDynamicItem protocol
var center: CGPoint = CGPoint.zero {
didSet {
updateFrame()
}
}
var transform: CGAffineTransform = CGAffineTransform.identity
var bounds: CGRect {
get {
return CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
}
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/DynamicItemGravity.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,142 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
enum AnimationSubType {
case moveX(CGFloat)
case moveY(CGFloat)
case moveXY(CGFloat,CGFloat)//Layer
case moveTo(CGPoint)
case color(UIColor)
case alpha(CGFloat)
case opacity(Float)//Layer
case rotateX(CGFloat)
case rotateY(CGFloat)
case rotate(CGFloat)
case rotateXY(CGFloat)
case width(CGFloat)
case height(CGFloat)
case size(CGSize)
case frame(CGRect)
case bounds(CGRect)
case scaleX(CGFloat)
case scaleY(CGFloat)
case scaleXY(CGFloat,CGFloat)
case cornerRadius(CGFloat)
case borderWidth(CGFloat)
case shadowRadius(CGFloat)
case zPosition(CGFloat)
case anchorPoint(CGPoint)
case anchorPointZ(CGFloat)
case shadowOffset(CGSize)
case shadowColor(UIColor)
case shadowOpacity(Float)
case tintColor(UIColor)
// UILabel,UITextView...
// case TextColor(UIColor)
}
//temp record for animation type
internal class AnimationType {
var mainType: AnimationStyle
var subType: AnimationSubType
init (type: AnimationStyle, subType: AnimationSubType) {
self.mainType = type
self.subType = subType
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/AnimationType.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 483 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
private let SolveForReverse = { (f: CFTimeInterval) in
return 1 - f
}
private let SolveForUnReverse = { (f: CFTimeInterval) in
return f
}
final class DynamicItemBasic<T: Interpolatable>: NSObject, UIDynamicItem, TimingType {
var duration: CFTimeInterval = 0.25
var delay: CFTimeInterval = 0.0
var timingFunction: TimingSolvable = TimingFunctionType.default.easing()
var from: T
var to: T
var render: (T) -> Void
var autoreverses = false
var repeatCount = 0
var completion: ((Bool) -> Void)?
var speed: Double = 1.0
var timeOffset: CFTimeInterval = 0.0 {
didSet {
updateFrame()
}
}
weak var behavior: UIDynamicBehavior?
//External data to store (performance)
fileprivate var externalData: Any?
fileprivate var complete = false
fileprivate var isReversing = false
fileprivate var solveProgress = SolveForUnReverse
fileprivate lazy var beginTime: CFTimeInterval = {
return CACurrentMediaTime()
}()
fileprivate lazy var epsilon: Double = {
return 1.0 / (self.duration * 1000.0)
}()
//MARK: Life cycle methods
init(from: T, to: T, render: @escaping (T) -> Void) {
self.from = from
self.to = to
self.render = render
if let fromColor = from as? UIColor {
let fromInfo = fromColor.colorInfo()
let toColor = to as! UIColor
let toInfo = toColor.colorInfo()
self.externalData = (fromInfo,toInfo)
}
}
deinit {
//do some thing
}
//MARK: update frame
fileprivate func updateFrame() {
let startTime = beginTime
var currentTime = CACurrentMediaTime() - startTime - delay
currentTime = max(0, currentTime) * speed + timeOffset
var progress = currentTime / duration
if progress >= 1.0 {
isReversing = autoreverses ? !isReversing : false
if repeatCount == 0 {
if isReversing {
progress = 0.0
beginTime = CACurrentMediaTime()
solveProgress = SolveForReverse
} else {
progress = 1.0
behavior?.cancel()
complete = true
self.completion?(complete)
}
}else {
if isReversing == false {
repeatCount -= 1
solveProgress = SolveForUnReverse
} else {
solveProgress = SolveForReverse
}
progress = 0.0
beginTime = CACurrentMediaTime()
}
}
let solveP = solveProgress(progress)
let adjustProgress = timingFunction.solveOn(solveP, epslion: epsilon)
let value = from.interpolate(adjustProgress, to: to, externalData: externalData)
self.render(value)
}
//MARK: UIDynamicItem protocol
var center: CGPoint = CGPoint.zero {
didSet {
updateFrame()
}
}
var transform: CGAffineTransform = CGAffineTransform.identity
var bounds: CGRect {
get {
return CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
}
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/DynamicItemBasic.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 975 |
```swift
//
// UIView+AnimateBehavior.swift
// StellarDemo
//
// Created by AugustRush on 6/21/16.
//
import UIKit
extension UIView: DriveAnimateBehaviors {
func behavior(forType type: AnimationType, step: AnimationStep) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
let mainType = type.mainType
let subType = type.subType
switch mainType {
case .basic:
behavior = createBasicAnimationWithType(subType, step: step)
case .snap(let d):
behavior = createSnapAnimationWithType(subType, damping: d)
case .attachment(let damping, let frequency):
behavior = createAttachmentAnimationWithType(subType, damping: damping, frequency: frequency)
case .gravity(let magnitude):
behavior = createGravityAnimationWithType(subType, magnitude: magnitude)
}
return behavior
}
//MARK: Basic
fileprivate func createBasicAnimationWithType(_ type: AnimationSubType, step: AnimationStep) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveX(let inc):
let from = self.center.x
let to = from + inc
let render = {(f: CGFloat) in
self.center.x = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .moveY(let inc):
let from = self.center.y
let to = from + inc
let render = {(f: CGFloat) in
self.center.y = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .moveTo(let point):
let from = self.center
let to = point
let render = {(p: CGPoint) in
self.center = p
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .color(let color):
let from = self.backgroundColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .alpha(let a):
let from = self.alpha
let to = a
let render = {(f: CGFloat) in
self.alpha = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .width(let w):
let from = self.frame.width
let to = w
let render = {(f: CGFloat) in
self.frame.size.width = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.layer.transform
let render = {(p: CGPoint) in
self.layer.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.layer.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.layer.cornerRadius = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.layer.borderWidth
let to = b
let render = {(f: CGFloat) in
self.layer.borderWidth = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.layer.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.layer.shadowRadius = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.layer.zPosition
let to = p
let render = {(f: CGFloat) in
self.layer.zPosition = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.layer.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.layer.anchorPoint = p
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.layer.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.layer.anchorPointZ = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.layer.shadowOffset
let to = size
let render = {(s: CGSize) in
self.layer.shadowOffset = s
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.layer.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.layer.shadowColor = c.cgColor
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.layer.shadowOpacity
let to = o
let render = {(f: Float) in
self.layer.shadowOpacity = f
}
behavior = basicBehavior(step, from: from, to: to, render: render)
case .tintColor(let color):
let from = self.tintColor
let to = color
let render = {(c: UIColor) in
self.tintColor = c
}
behavior = basicBehavior(step, from: from!, to: to, render: render)
default:
fatalError("Should Not be excute forever!")
}
return behavior
}
//MARK: Snap
fileprivate func createSnapAnimationWithType(_ type: AnimationSubType, damping: CGFloat) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveX(let inc):
let from = self.center.x
let to = from + inc
let render = {(f: CGFloat) in
self.center.x = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .moveY(let inc):
let from = self.center.y
let to = from + inc
let render = {(f: CGFloat) in
self.center.y = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .moveTo(let point):
let from = self.center
let to = point
let render = {(p: CGPoint) in
self.center = p
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .color(let color):
let from = self.backgroundColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .alpha(let a):
let from = self.alpha
let to = a
let render = {(f: CGFloat) in
self.alpha = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .width(let w):
let from = self.frame.width
let to = w
let render = {(f: CGFloat) in
self.frame.size.width = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.layer.transform
let render = {(p: CGPoint) in
self.layer.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.layer.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.layer.cornerRadius = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.layer.borderWidth
let to = b
let render = {(f: CGFloat) in
self.layer.borderWidth = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.layer.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.layer.shadowRadius = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.layer.zPosition
let to = p
let render = {(f: CGFloat) in
self.layer.zPosition = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.layer.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.layer.anchorPoint = p
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.layer.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.layer.anchorPointZ = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.layer.shadowOffset
let to = size
let render = {(s: CGSize) in
self.layer.shadowOffset = s
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.layer.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.layer.shadowColor = c.cgColor
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.layer.shadowOpacity
let to = o
let render = {(f: Float) in
self.layer.shadowOpacity = f
}
behavior = snapBehavior(damping, from: from, to: to, render: render)
case .tintColor(let color):
let from = self.tintColor
let to = color
let render = {(c: UIColor) in
self.tintColor = c
}
behavior = snapBehavior(damping, from: from!, to: to, render: render)
default:
fatalError("Should Not be excute forever!")
}
return behavior
}
//MARK: Attachment
fileprivate func createAttachmentAnimationWithType(_ type: AnimationSubType, damping: CGFloat, frequency: CGFloat) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveX(let inc):
let from = self.center.x
let to = from + inc
let render = {(f: CGFloat) in
self.center.x = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .moveY(let inc):
let from = self.center.y
let to = from + inc
let render = {(f: CGFloat) in
self.center.y = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .moveTo(let point):
let from = self.center
let to = point
let render = {(p: CGPoint) in
self.center = p
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .color(let color):
let from = self.backgroundColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .alpha(let a):
let from = self.alpha
let to = a
let render = {(f: CGFloat) in
self.alpha = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .width(let w):
let from = self.frame.width
let to = w
let render = {(f: CGFloat) in
self.frame.size.width = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.layer.transform
let render = {(p: CGPoint) in
self.layer.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.layer.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.layer.cornerRadius = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.layer.borderWidth
let to = b
let render = {(f: CGFloat) in
self.layer.borderWidth = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.layer.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.layer.shadowRadius = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.layer.zPosition
let to = p
let render = {(f: CGFloat) in
self.layer.zPosition = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.layer.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.layer.anchorPoint = p
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.layer.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.layer.anchorPointZ = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.layer.shadowOffset
let to = size
let render = {(s: CGSize) in
self.layer.shadowOffset = s
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.layer.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.layer.shadowColor = c.cgColor
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.layer.shadowOpacity
let to = o
let render = {(f: Float) in
self.layer.shadowOpacity = f
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .tintColor(let color):
let from = self.tintColor
let to = color
let render = {(c: UIColor) in
self.tintColor = c
}
behavior = attachmentBehavior(damping, frequency: frequency, from: from!, to: to, render: render)
default:
fatalError("Should Not be excute forever!")
}
return behavior
}
//MARK: Gravity
fileprivate func createGravityAnimationWithType(_ type: AnimationSubType, magnitude: Double) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch type {
case .moveX(let inc):
let from = self.center.x
let to = from + inc
let render = {(f: CGFloat) in
self.center.x = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .moveY(let inc):
let from = self.center.y
let to = from + inc
let render = {(f: CGFloat) in
self.center.y = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .moveTo(let point):
let from = self.center
let to = point
let render = {(p: CGPoint) in
self.center = p
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .color(let color):
let from = self.backgroundColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .alpha(let a):
let from = self.alpha
let to = a
let render = {(f: CGFloat) in
self.alpha = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .width(let w):
let from = self.frame.width
let to = w
let render = {(f: CGFloat) in
self.frame.size.width = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, f, 1, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, 1, y, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.layer.transform
let render = {(p: CGPoint) in
self.layer.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .cornerRadius(let r):
let from = self.layer.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.layer.cornerRadius = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .borderWidth(let b):
let from = self.layer.borderWidth
let to = b
let render = {(f: CGFloat) in
self.layer.borderWidth = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowRadius(let s):
let from = self.layer.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.layer.shadowRadius = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .zPosition(let p):
let from = self.layer.zPosition
let to = p
let render = {(f: CGFloat) in
self.layer.zPosition = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .anchorPoint(let point):
let from = self.layer.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.layer.anchorPoint = p
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .anchorPointZ(let z):
let from = self.layer.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.layer.anchorPointZ = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowOffset(let size):
let from = self.layer.shadowOffset
let to = size
let render = {(s: CGSize) in
self.layer.shadowOffset = s
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowColor(let c):
let color = self.layer.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.layer.shadowColor = c.cgColor
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .shadowOpacity(let o):
let from = self.layer.shadowOpacity
let to = o
let render = {(f: Float) in
self.layer.shadowOpacity = f
}
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .tintColor(let color):
let from = self.tintColor
let to = color
let render = {(c: UIColor) in
self.tintColor = c
}
behavior = gravityBehavior(magnitude, from: from!, to: to, render: render)
// case .TextColor(let color):
// let fromColor = self.performSelector(Selector("textColor")).takeUnretainedValue() as? UIColor
// let from = fromColor ?? UIColor.clearColor()
// let to = color
// let render = { (cc: UIColor) in
// self.performSelector(Selector("setTextColor:"),withObject: cc)
// }
// behavior = basicBehavior(step, from: from, to: to, render: render)
default:
fatalError("Should Not be excute forever!")
}
return behavior
}
//MARK: Private methods
fileprivate func basicBehavior<T: Interpolatable>(_ step: AnimationStep,from: T, to: T, render: @escaping ((T) -> Void)) -> UIDynamicBehavior {
let item = DynamicItemBasic(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.duration = step.duration
item.timingFunction = step.timing.easing()
item.delay = step.delay
item.repeatCount = step.repeatCount
item.autoreverses = step.autoreverses
return push
}
fileprivate func snapBehavior<T: Vectorial>(_ damping: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let snap = item.snapBehavior(point, damping: damping)
item.behavior = snap
return snap
}
fileprivate func attachmentBehavior<T: Vectorial>(_ damping: CGFloat, frequency: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let attachment = item.attachmentBehavior(point, length: 0.0, damping: damping, frequency: frequency)
item.behavior = attachment
return attachment
}
fileprivate func gravityBehavior<T: Interpolatable>(_ magnitude: Double, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItemGravity(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.magnitude = magnitude
return push
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/UIView+AnimateBehavior.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 8,819 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol BasicConfigurable: BasicChainable {
func duration(_ d: CFTimeInterval) -> BasicConfigurable
func easing(_ type: TimingFunctionType) -> BasicConfigurable
func delay(_ d: CFTimeInterval) -> BasicConfigurable
func reverses() -> BasicConfigurable
func repeatCount(_ count: Int) -> BasicConfigurable
}
//CALayer
public protocol BasicConfigurable1: BasicChainable1 {
func duration(_ d: CFTimeInterval) -> BasicConfigurable1
func easing(_ type: TimingFunctionType) -> BasicConfigurable1
func delay(_ d: CFTimeInterval) -> BasicConfigurable1
func reverses() -> BasicConfigurable1
func repeatCount(_ count: Int) -> BasicConfigurable1
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/BasicConfigurable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 369 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public class Vector4 {
var one: Double = 0
var two: Double = 0
var three: Double = 0
var four: Double = 0
convenience init(_ fourLatitude: (Double,Double,Double,Double)) {
self.init()
self.one = fourLatitude.0
self.two = fourLatitude.1
self.three = fourLatitude.2
self.four = fourLatitude.3
}
}
public protocol Vectorial {
func convert(_ p: Vector4) -> Self
func reverse() -> Vector4
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/Vectorial.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 331 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
extension UILabel {
// public func makeTextColor(color: UIColor) -> UIView {
// let type = AnimationType(type: .Basic, subType: .TextColor(color))
// context.addAnimationType(type)
// return self
// }
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/UILabel+Stellar.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 254 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
enum PhysicalDirection {
case left
case right
case up
case down
case Angle(CGFloat)
case vector(CGFloat,CGFloat)
func angle() -> CGFloat {
switch self {
case .Angle(let a):
return a
case .vector(let x, let y):
return atan2(y, x)
case .left:
return atan2(0, -1)
case .right:
return atan2(0, 1)
case .up:
return atan2(-1, 0)
case .down:
return atan2(1, 0)
}
}
}
extension UIDynamicItem {
//gravity
func gravityBehavior(_ magnitude: CGFloat = 1.0, direction: PhysicalDirection = .down) -> UIGravityBehavior {
let gravity = UIGravityBehavior()
switch direction {
case .Angle(let a):
gravity.setAngle(a, magnitude: magnitude)
case .left:
gravity.gravityDirection = CGVector(dx: -1, dy: 0)
case .right:
gravity.gravityDirection = CGVector(dx: 1, dy: 0)
case .up:
gravity.gravityDirection = CGVector(dx: 0, dy: -1)
case .down:
gravity.gravityDirection = CGVector(dx: 0, dy: 1)
case .vector(let x, let y):
gravity.gravityDirection = CGVector(dx: x, dy: y)
}
gravity.magnitude = magnitude
gravity.addItem(self)
return gravity
}
//snap
func snapBehavior(_ toPoint: CGPoint, damping: CGFloat = 0.5) -> UISnapBehavior {
let snap = UISnapBehavior(item: self,snapTo: toPoint)
snap.damping = damping
return snap
}
//attachment
func attachmentBehavior(_ toAnchor: CGPoint, length: CGFloat = 0.0, damping: CGFloat = 0.5, frequency: CGFloat = 1.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedToAnchor: toAnchor)
attachment.length = length
attachment.damping = damping
attachment.frequency = frequency
return attachment
}
func attachmentBehavior(_ toItem: UIDynamicItem, damping: CGFloat = 0.5, frequency: CGFloat = 1.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedTo: toItem)
attachment.damping = damping
attachment.frequency = frequency
return attachment
}
func attachmentBehavior(_ toItem: UIDynamicItem, damping: CGFloat = 0.5, frequency: CGFloat = 1.0, length: CGFloat = 0.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedTo: toItem)
attachment.damping = damping
attachment.length = length
attachment.frequency = frequency
return attachment
}
//push
func pushBehavior(_ direction: CGVector, mode:UIPushBehaviorMode = .instantaneous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
push.pushDirection = direction
push.magnitude = magnitude
return push
}
func pushBehavior(_ direction: PhysicalDirection, mode:UIPushBehaviorMode = .instantaneous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
switch direction {
case .Angle(let a):
push.setAngle(a, magnitude: magnitude)
case .left:
push.pushDirection = CGVector(dx: -1, dy: 0)
case .right:
push.pushDirection = CGVector(dx: 1, dy: 0)
case .up:
push.pushDirection = CGVector(dx: 0, dy: -1)
case .down:
push.pushDirection = CGVector(dx: 0, dy: 1)
case .vector(let x, let y):
push.pushDirection = CGVector(dx: x, dy: y)
}
push.magnitude = magnitude
return push
}
func pushBehavior(_ angle: CGFloat, mode:UIPushBehaviorMode = .instantaneous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
push.angle = angle
push.magnitude = magnitude
return push
}
//collision
func collisionBehavior(_ mode: UICollisionBehaviorMode = .boundaries) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
collision.addItem(self)
return collision
}
func collisionBehavior(_ mode: UICollisionBehaviorMode = .boundaries, path: UIBezierPath) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
collision.addBoundary(withIdentifier: identifier as NSCopying, for: path)
collision.addItem(self)
return collision
}
func collisionBehavior(_ mode: UICollisionBehaviorMode = .boundaries, fromPoint: CGPoint, toPoint: CGPoint) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
collision.addBoundary(withIdentifier: identifier as NSCopying, from: fromPoint, to: toPoint)
collision.addItem(self)
return collision
}
//itemBehavior
func itemBehavior(_ elasticity: CGFloat = 0.5, friction: CGFloat = 0.5, density: CGFloat = 1, resistance: CGFloat = 0, angularResistance: CGFloat = 0, allowsRotation: Bool = true) -> UIDynamicItemBehavior {
let behavior = UIDynamicItemBehavior()
behavior.addItem(self)
behavior.elasticity = elasticity
behavior.friction = friction
behavior.density = density
behavior.resistance = resistance
behavior.angularResistance = angularResistance
behavior.allowsRotation = allowsRotation
return behavior
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/DynamicItem+Behavior.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,568 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
import CoreGraphics
public typealias Scalar = Double
/// A bezier curve, often used to calculate timing functions.
public struct UnitBezier {
/// The horizontal component of the first control point.
public var p1x: Scalar
/// The vertical component of the first control point.
public var p1y: Scalar
/// The horizontal component of the second control point.
public var p2x: Scalar
/// The vertical component of the second control point.
public var p2y: Scalar
/// Creates a new `UnitBezier` instance.
public init(p1x: Scalar, p1y: Scalar, p2x: Scalar, p2y: Scalar) {
self.p1x = p1x
self.p1y = p1y
self.p2x = p2x
self.p2y = p2y
}
/// Calculates the resulting `y` for given `x`.
///
/// - parameter x: The value to solve for.
/// - parameter epsilon: The required precision of the result (where `x * epsilon` is the maximum time segment to be evaluated).
/// - returns: The solved `y` value.
public func solve(_ x: Scalar, epsilon: Scalar) -> Scalar {
return UnitBezierSolver(bezier: self).solve(x, eps: epsilon)
}
}
extension UnitBezier: Equatable { }
extension UnitBezier: TimingSolvable {
func solveOn(_ time: Double, epslion: Double) -> Double {
return self.solve(time, epsilon: epslion)
}
}
/// Equatable.
public func ==(lhs: UnitBezier, rhs: UnitBezier) -> Bool {
return lhs.p1x == rhs.p1x
&& lhs.p1y == rhs.p1y
&& lhs.p2x == rhs.p2x
&& lhs.p2y == rhs.p2y
}
// Ported to Swift from WebCore:
// path_to_url
/*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
private struct UnitBezierSolver {
fileprivate let ax: Scalar
fileprivate let bx: Scalar
fileprivate let cx: Scalar
fileprivate let ay: Scalar
fileprivate let by: Scalar
fileprivate let cy: Scalar
init(bezier: UnitBezier) {
self.init(p1x: bezier.p1x, p1y: bezier.p1y, p2x: bezier.p2x, p2y: bezier.p2y)
}
init(p1x: Scalar, p1y: Scalar, p2x: Scalar, p2y: Scalar) {
// Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
cx = 3.0 * p1x
bx = 3.0 * (p2x - p1x) - cx
ax = 1.0 - cx - bx
cy = 3.0 * p1y
by = 3.0 * (p2y - p1y) - cy
ay = 1.0 - cy - by
}
func sampleCurveX(_ t: Scalar) -> Scalar {
return ((ax * t + bx) * t + cx) * t
}
func sampleCurveY(_ t: Scalar) -> Scalar {
return ((ay * t + by) * t + cy) * t
}
func sampleCurveDerivativeX(_ t: Scalar) -> Scalar {
return (3.0 * ax * t + 2.0 * bx) * t + cx
}
func solveCurveX(_ x: Scalar, eps: Scalar) -> Scalar {
var t0: Scalar = 0.0
var t1: Scalar = 0.0
var t2: Scalar = 0.0
var x2: Scalar = 0.0
var d2: Scalar = 0.0
// First try a few iterations of Newton's method -- normally very fast.
t2 = x
for _ in 0..<8 {
x2 = sampleCurveX(t2) - x
if abs(x2) < eps {
return t2
}
d2 = sampleCurveDerivativeX(t2)
if abs(d2) < 1e-6 {
break
}
t2 = t2 - x2 / d2
}
// Fall back to the bisection method for reliability.
t0 = 0.0
t1 = 1.0
t2 = x
if t2 < t0 {
return t0
}
if t2 > t1 {
return t1
}
while t0 < t1 {
x2 = sampleCurveX(t2)
if abs(x2-x) < eps {
return t2
}
if x > x2 {
t0 = t2
} else {
t1 = t2
}
t2 = (t1-t0) * 0.5 + t0
}
return t2
}
func solve(_ x: Scalar, eps: Scalar) -> Scalar {
return sampleCurveY(solveCurveX(x, eps: eps))
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/UnitBezier.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,613 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol SnapConfigurable: BasicChainable {
func snap(_ damping: CGFloat) -> SnapConfigurable
}
public protocol SnapConfigurable1: BasicChainable1 {
func snap(_ damping: CGFloat) -> SnapConfigurable1
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/SnapConfigurable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 253 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
extension CALayer: BasicConfigurable1, SnapConfigurable1, AttachmentConfigurable1, GravityConfigurable1, StepControllable {
//MARK: animation methods
public func moveTo(_ point: CGPoint) -> CALayer {
let type = AnimationType(type: .basic, subType: .moveTo(point))
context.addAnimationType(type)
return self
}
public func makeColor(_ color: UIColor) -> CALayer {
let type = AnimationType(type: .basic, subType: .color(color))
context.addAnimationType(type)
return self
}
public func makeOpacity(_ opacity: Float) -> CALayer {
let type = AnimationType(type: .basic, subType: .opacity(opacity))
context.addAnimationType(type)
return self
}
public func rotate(_ z: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .rotate(z))
context.addAnimationType(type)
return self
}
public func rotateX(_ x: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .rotateX(x))
context.addAnimationType(type)
return self
}
public func rotateY(_ y: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .rotateY(y))
context.addAnimationType(type)
return self
}
public func rotateXY(_ xy: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .rotateXY(xy))
context.addAnimationType(type)
return self
}
public func makeWidth(_ width: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .width(width))
context.addAnimationType(type)
return self
}
public func makeHeight(_ height: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .height(height))
context.addAnimationType(type)
return self
}
public func makeSize(_ size: CGSize) -> CALayer {
let type = AnimationType(type: .basic, subType: .size(size))
context.addAnimationType(type)
return self
}
public func makeFrame(_ frame: CGRect) -> CALayer {
let type = AnimationType(type: .basic, subType: .frame(frame))
context.addAnimationType(type)
return self
}
public func makeBounds(_ bounds: CGRect) -> CALayer {
let type = AnimationType(type: .basic, subType: .bounds(bounds))
context.addAnimationType(type)
return self
}
public func scaleX(_ x: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .scaleX(x))
context.addAnimationType(type)
return self
}
public func scaleY(_ y: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .scaleY(y))
context.addAnimationType(type)
return self
}
public func scaleXY(_ x: CGFloat, _ y: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .scaleXY(x,y))
context.addAnimationType(type)
return self
}
public func cornerRadius(_ radius: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .cornerRadius(radius))
context.addAnimationType(type)
return self
}
public func borderWidth(_ width: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .borderWidth(width))
context.addAnimationType(type)
return self
}
public func shadowRadius(_ radius: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .shadowRadius(radius))
context.addAnimationType(type)
return self
}
public func zPosition(_ position: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .zPosition(position))
context.addAnimationType(type)
return self
}
public func anchorPoint(_ point: CGPoint) -> CALayer {
let type = AnimationType(type: .basic, subType: .anchorPoint(point))
context.addAnimationType(type)
return self
}
public func anchorPointZ(_ z: CGFloat) -> CALayer {
let type = AnimationType(type: .basic, subType: .anchorPointZ(z))
context.addAnimationType(type)
return self
}
public func shadowOffset(_ offset: CGSize) -> CALayer {
let type = AnimationType(type: .basic, subType: .shadowOffset(offset))
context.addAnimationType(type)
return self
}
public func shadowColor(_ color: UIColor) -> CALayer {
let type = AnimationType(type: .basic, subType: .shadowColor(color))
context.addAnimationType(type)
return self
}
public func shadowOpacity(_ opacity: Float) -> CALayer {
let type = AnimationType(type: .basic, subType: .shadowOpacity(opacity))
context.addAnimationType(type)
return self
}
public func makeTintColor(_ color: UIColor) -> CALayer {
let type = AnimationType(type: .basic, subType: .tintColor(color))
context.addAnimationType(type)
return self
}
public func completion(_ c: @escaping () -> Void) -> CALayer {
context.changeCompletion(c)
return self
}
//MARK: Physical Animation
//Snap
public func snap(_ damping: CGFloat = 0.5) -> SnapConfigurable1 {
context.changeMainType(.snap(damping))
return self
}
//Attachment
public func attachment(_ damping: CGFloat = 0.5, frequency: CGFloat = 0.5) -> AttachmentConfigurable1 {
context.changeMainType(.attachment(damping, frequency))
return self
}
//Gravity
public func gravity(_ magnitude: Double = 1.0) -> GravityConfigurable1 {
context.changeMainType(.gravity(magnitude))
return self
}
//MARK: Basic Animation configurations
public func duration(_ d: CFTimeInterval) -> BasicConfigurable1 {
context.changeDuration(d)
return self
}
public func easing(_ type: TimingFunctionType) -> BasicConfigurable1 {
context.changeEasing(type)
return self
}
public func delay(_ d: CFTimeInterval) -> BasicConfigurable1 {
context.changeDelay(d)
return self
}
public func autoreverses() -> BasicConfigurable1 {
context.changeAutoreverses(true)
return self
}
public func repeatCount(_ count: Int) -> BasicConfigurable1 {
context.changeRepeatCount(count)
return self
}
//MARK: Chainable methods
public func then() -> CALayer {
context.makeNextStep()
return self
}
//commit to excute
public func animate() -> Void {
context.commit()
}
//MARK: StepControllable methods
public func cancelAllRemaining() {
context.removeAllRemaining()
}
//Private Context for view and layer
fileprivate var context: AnimationContext {
get {
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
var context = self.value(forKey: identifier) as? AnimationContext
if context == nil {
context = AnimationContext(object: self)
self.setValue(context!, forKey: identifier)
}
return context!
}
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/CALayer+Stellar.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,902 |
```swift
//
// TimingSolvable.swift
// StellarDemo
//
// Created by AugustRush on 6/28/16.
//
import Foundation
protocol TimingSolvable {
func solveOn(_ time: Double, epslion: Double) -> Double
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/TimingSolvable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 57 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol AttachmentConfigurable: BasicChainable {
func attachment(_ damping: CGFloat, frequency: CGFloat) -> AttachmentConfigurable
}
public protocol AttachmentConfigurable1: BasicChainable1 {
func attachment(_ damping: CGFloat, frequency: CGFloat) -> AttachmentConfigurable1
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/AttachmentConfigurable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 261 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
/// A set of preset bezier curves.
public enum TimingFunctionType {
/// Equivalent to `kCAMediaTimingFunctionDefault`.
case `default`
/// Equivalent to `kCAMediaTimingFunctionEaseIn`.
case easeIn
/// Equivalent to `kCAMediaTimingFunctionEaseOut`.
case easeOut
/// Equivalent to `kCAMediaTimingFunctionEaseInEaseOut`.
case easeInEaseOut
/// No easing.
case linear
/// Inspired by the default curve in Google Material Design.
case swiftOut
///
case backEaseIn
///
case backEaseOut
///
case backEaseInOut
///
case bounceOut
///
case sine
///
case circ
///
case exponentialIn
///
case exponentialOut
///
case elasticIn
///
case bounceReverse
///
case elasticOut
/// custom
case custom(Double, Double, Double, Double)
func easing() -> TimingSolvable {
switch self {
case .default:
return UnitBezier(p1x: 0.25, p1y: 0.1, p2x: 0.25, p2y: 1.0)
case .easeIn:
return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 1.0, p2y: 1.0)
case .easeOut:
return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 0.58, p2y: 1.0)
case .easeInEaseOut:
return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 0.58, p2y: 1.0)
case .linear:
return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 1.0, p2y: 1.0)
case .swiftOut:
return UnitBezier(p1x: 0.4, p1y: 0.0, p2x: 0.2, p2y: 1.0)
case .backEaseIn:
return EasingContainer(easing: { (t: Double) in
return t * t * t - t * sin(t * M_PI)
})
case .backEaseOut:
return EasingContainer(easing: { (t: Double) in
let f = (1 - t);
return 1 - (f * f * f - f * sin(f * M_PI));
})
case .backEaseInOut:
return EasingContainer(easing: { (t: Double) in
if(t < 0.5) {
let f = 2 * t;
return 0.5 * (f * f * f - f * sin(f * M_PI));
} else {
let f = (1.0 - (2.0 * t - 1.0));
let cubic = f * f * f
return 0.5 * (1.0 - (cubic - f * sin(f * M_PI))) + 0.5;
}
})
case .bounceOut:
return EasingContainer(easing: { (t: Double) in
if(t < 4/11.0){
return (121 * t * t)/16.0;
} else if(t < 8/11.0){
return (363/40.0 * t * t) - (99/10.0 * t) + 17/5.0;
}else if(t < 9/10.0){
return (4356/361.0 * t * t) - (35442/1805.0 * t) + 16061/1805.0;
}else{
return (54/5.0 * t * t) - (513/25.0 * t) + 268/25.0;
}
})
case .sine:
return EasingContainer(easing: { (t: Double) in
return 1 - cos( t * M_PI / 2.0)
})
case .circ:
return EasingContainer(easing: { (t: Double) in
return 1 - sqrt( 1.0 - t * t )
})
case .exponentialIn:
return EasingContainer(easing: { (t: Double) in
return (t == 0.0) ? t : pow(2, 10 * (t - 1))
})
case .exponentialOut:
return EasingContainer(easing: { (t: Double) in
return (t == 1.0) ? t : 1 - pow(2, -10 * t)
})
case .elasticIn:
return EasingContainer(easing: { (t: Double) in
return sin(13.0 * M_PI_2 * t) * pow(2, 10 * (t - 1))
})
case .elasticOut:
return EasingContainer(easing: { (t: Double) in
return sin(-13.0 * M_PI_2 * (t + 1)) * pow(2, -10 * t) + 1.0;
})
case .bounceReverse:
return EasingContainer(easing: { (t: Double) in
var bounce: Double = 4.0
var pow2 = 0.0
repeat {
bounce = bounce - 1.0
pow2 = pow(2, bounce)
} while (t < (pow2 - 1.0 ) / 11.0)
return 1 / pow( 4, 3 - bounce ) - 7.5625 * pow( ( pow2 * 3 - 2 ) / 22 - t, 2 );
})
case .custom(let p1x,let p1y,let p2x,let p2y):
return UnitBezier(p1x: p1x, p1y: p1y, p2x: p2x, p2y: p2y)
}
}
}
class EasingContainer: TimingSolvable {
let easing: (Double) -> Double
init(easing: @escaping (Double) -> Double) {
self.easing = easing
}
//
func solveOn(_ time: Double, epslion: Double) -> Double {
return self.easing(time)
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemo/MyPlayground.playground/Sources/Sources/TimingFunction.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,671 |
```swift
//
// StellarDemoUITests.swift
// StellarDemoUITests
//
// Created by AugustRush on 5/7/16.
//
import XCTest
class StellarDemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests its important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemoUITests/StellarDemoUITests.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 249 |
```swift
//
// StellarDemoTests.swift
// StellarDemoTests
//
// Created by AugustRush on 5/7/16.
//
import XCTest
@testable import StellarDemo
class StellarDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
``` | /content/code_sandbox/StellarDemo/StellarDemoTests/StellarDemoTests.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 199 |
```swift
//
// StellarTests.swift
// StellarTests
//
// Created by AugustRush on 6/6/16.
//
import XCTest
@testable import Stellar
class StellarTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
``` | /content/code_sandbox/StellarDemo/StellarTests/StellarTests.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 196 |
```objective-c
//
// Stellar.h
// Stellar
//
// Created by AugustRush on 6/6/16.
//
#import <UIKit/UIKit.h>
//! Project version number for Stellar.
FOUNDATION_EXPORT double StellarVersionNumber;
//! Project version string for Stellar.
FOUNDATION_EXPORT const unsigned char StellarVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Stellar/PublicHeader.h>
``` | /content/code_sandbox/StellarDemo/Stellar/Stellar.h | objective-c | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 91 |
```objective-c
//
// Stellar.h
// Stellar
//
// Created by AugustRush on 6/6/16.
//
#import <UIKit/UIKit.h>
//! Project version number for Stellar.
FOUNDATION_EXPORT double StellarVersionNumber;
//! Project version string for Stellar.
FOUNDATION_EXPORT const unsigned char StellarVersionString[];
#import "Stellar-Swift.h"
// In this header, you should import all the public headers of your framework using statements like #import <Stellar/PublicHeader.h>
``` | /content/code_sandbox/Carthage/Build/iOS/Stellar.framework/Headers/Stellar.h | objective-c | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 100 |
```objective-c
// Generated by Apple Swift version 3.1 (swiftlang-802.0.51 clang-802.0.41)
#pragma clang diagnostic push
#if defined(__has_include) && __has_include(<swift/objc-prologue.h>)
# include <swift/objc-prologue.h>
#endif
#pragma clang diagnostic ignored "-Wauto-import"
#include <objc/NSObject.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#if !defined(SWIFT_TYPEDEFS)
# define SWIFT_TYPEDEFS 1
# if defined(__has_include) && __has_include(<uchar.h>)
# include <uchar.h>
# elif !defined(__cplusplus) || __cplusplus < 201103L
typedef uint_least16_t char16_t;
typedef uint_least32_t char32_t;
# endif
typedef float swift_float2 __attribute__((__ext_vector_type__(2)));
typedef float swift_float3 __attribute__((__ext_vector_type__(3)));
typedef float swift_float4 __attribute__((__ext_vector_type__(4)));
typedef double swift_double2 __attribute__((__ext_vector_type__(2)));
typedef double swift_double3 __attribute__((__ext_vector_type__(3)));
typedef double swift_double4 __attribute__((__ext_vector_type__(4)));
typedef int swift_int2 __attribute__((__ext_vector_type__(2)));
typedef int swift_int3 __attribute__((__ext_vector_type__(3)));
typedef int swift_int4 __attribute__((__ext_vector_type__(4)));
typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2)));
typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3)));
typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4)));
#endif
#if !defined(SWIFT_PASTE)
# define SWIFT_PASTE_HELPER(x, y) x##y
# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)
#endif
#if !defined(SWIFT_METATYPE)
# define SWIFT_METATYPE(X) Class
#endif
#if !defined(SWIFT_CLASS_PROPERTY)
# if __has_feature(objc_class_property)
# define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__
# else
# define SWIFT_CLASS_PROPERTY(...)
# endif
#endif
#if defined(__has_attribute) && __has_attribute(objc_runtime_name)
# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X)))
#else
# define SWIFT_RUNTIME_NAME(X)
#endif
#if defined(__has_attribute) && __has_attribute(swift_name)
# define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X)))
#else
# define SWIFT_COMPILE_NAME(X)
#endif
#if defined(__has_attribute) && __has_attribute(objc_method_family)
# define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X)))
#else
# define SWIFT_METHOD_FAMILY(X)
#endif
#if defined(__has_attribute) && __has_attribute(noescape)
# define SWIFT_NOESCAPE __attribute__((noescape))
#else
# define SWIFT_NOESCAPE
#endif
#if defined(__has_attribute) && __has_attribute(warn_unused_result)
# define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
# define SWIFT_WARN_UNUSED_RESULT
#endif
#if !defined(SWIFT_CLASS_EXTRA)
# define SWIFT_CLASS_EXTRA
#endif
#if !defined(SWIFT_PROTOCOL_EXTRA)
# define SWIFT_PROTOCOL_EXTRA
#endif
#if !defined(SWIFT_ENUM_EXTRA)
# define SWIFT_ENUM_EXTRA
#endif
#if !defined(SWIFT_CLASS)
# if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted)
# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA
# define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# else
# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# endif
#endif
#if !defined(SWIFT_PROTOCOL)
# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
# define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
#endif
#if !defined(SWIFT_EXTENSION)
# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__)
#endif
#if !defined(OBJC_DESIGNATED_INITIALIZER)
# if defined(__has_attribute) && __has_attribute(objc_designated_initializer)
# define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
# else
# define OBJC_DESIGNATED_INITIALIZER
# endif
#endif
#if !defined(SWIFT_ENUM)
# define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_EXTRA _name : _type
# if defined(__has_feature) && __has_feature(generalized_swift_name)
# define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_EXTRA _name : _type
# else
# define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) SWIFT_ENUM(_type, _name)
# endif
#endif
#if !defined(SWIFT_UNAVAILABLE)
# define SWIFT_UNAVAILABLE __attribute__((unavailable))
#endif
#if !defined(SWIFT_UNAVAILABLE_MSG)
# define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg)))
#endif
#if !defined(SWIFT_AVAILABILITY)
# define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__)))
#endif
#if !defined(SWIFT_DEPRECATED)
# define SWIFT_DEPRECATED __attribute__((deprecated))
#endif
#if !defined(SWIFT_DEPRECATED_MSG)
# define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__)))
#endif
#if defined(__has_feature) && __has_feature(modules)
@import QuartzCore;
@import CoreGraphics;
@import CoreFoundation;
@import UIKit;
#endif
#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch"
#pragma clang diagnostic ignored "-Wduplicate-method-arg"
@interface CALayer (SWIFT_EXTENSION(Stellar))
@end
@class UIColor;
@interface CALayer (SWIFT_EXTENSION(Stellar))
- (nonnull instancetype)moveX:(CGFloat)increment SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)moveY:(CGFloat)increment SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)moveTo:(CGPoint)point SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeColor:(UIColor * _Nonnull)color SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeOpacity:(float)opacity SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeAlpha:(CGFloat)alpha SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotate:(CGFloat)z SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotateX:(CGFloat)x SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotateY:(CGFloat)y SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotateXY:(CGFloat)xy SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeWidth:(CGFloat)width SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeHeight:(CGFloat)height SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeSize:(CGSize)size SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeFrame:(CGRect)frame SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeBounds:(CGRect)bounds SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)scaleX:(CGFloat)x SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)scaleY:(CGFloat)y SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)scaleXY:(CGFloat)x :(CGFloat)y SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)cornerRadius:(CGFloat)radius SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)borderWidth:(CGFloat)width SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowRadius:(CGFloat)radius SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)zPosition:(CGFloat)position SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)anchorPoint:(CGPoint)point SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)anchorPointZ:(CGFloat)z SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowOffset:(CGSize)offset SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowColor:(UIColor * _Nonnull)color SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowOpacity:(float)opacity SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeTintColor:(UIColor * _Nonnull)color SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)completion:(void (^ _Nonnull)(void))c SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)snap:(CGFloat)damping SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)attachment:(CGFloat)damping frequency:(CGFloat)frequency SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)gravity:(double)magnitude SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)duration:(CFTimeInterval)d SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)delay:(CFTimeInterval)d SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)autoreverses SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)repeatCount:(NSInteger)count SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)then SWIFT_WARN_UNUSED_RESULT;
- (void)animate;
- (void)cancelAllRemaining;
@end
@interface UIColor (SWIFT_EXTENSION(Stellar))
- (nonnull instancetype)interpolate:(double)progress to:(UIColor * _Nonnull)to externalData:(id _Nullable)externalData SWIFT_WARN_UNUSED_RESULT;
@end
@interface UIDynamicBehavior (SWIFT_EXTENSION(Stellar))
@end
@interface UILabel (SWIFT_EXTENSION(Stellar))
@end
@interface UITextView (SWIFT_EXTENSION(Stellar))
@end
@interface UIView (SWIFT_EXTENSION(Stellar))
- (BOOL)configureWithJSON:(NSString * _Nonnull)str error:(NSError * _Nullable * _Nullable)error;
@end
@interface UIView (SWIFT_EXTENSION(Stellar))
@end
@interface UIView (SWIFT_EXTENSION(Stellar))
- (nonnull instancetype)moveX:(CGFloat)increment SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)moveY:(CGFloat)increment SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)moveTo:(CGPoint)point SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeColor:(UIColor * _Nonnull)color SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeAlpha:(CGFloat)alpha SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotate:(CGFloat)z SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotateX:(CGFloat)x SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotateY:(CGFloat)y SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)rotateXY:(CGFloat)xy SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeWidth:(CGFloat)width SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeHeight:(CGFloat)height SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeSize:(CGSize)size SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeFrame:(CGRect)frame SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeBounds:(CGRect)bounds SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)scaleX:(CGFloat)x SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)scaleY:(CGFloat)y SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)scaleXY:(CGFloat)x :(CGFloat)y SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)cornerRadius:(CGFloat)radius SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)borderWidth:(CGFloat)width SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowRadius:(CGFloat)radius SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)zPosition:(CGFloat)position SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)anchorPoint:(CGPoint)point SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)anchorPointZ:(CGFloat)z SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowOffset:(CGSize)offset SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowColor:(UIColor * _Nonnull)color SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)shadowOpacity:(float)opacity SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)makeTintColor:(UIColor * _Nonnull)color SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)completion:(void (^ _Nonnull)(void))c SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)snap:(CGFloat)damping SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)attachment:(CGFloat)damping frequency:(CGFloat)frequency SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)gravity:(double)magnitude SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)duration:(CFTimeInterval)d SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)delay:(CFTimeInterval)d SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)autoreverses SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)repeatCount:(NSInteger)count SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)then SWIFT_WARN_UNUSED_RESULT;
- (void)animate;
- (void)cancelAllRemaining;
@end
#pragma clang diagnostic pop
``` | /content/code_sandbox/Carthage/Build/iOS/Stellar.framework/Headers/Stellar-Swift.h | objective-c | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 2,992 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public enum AnimationStyle {
case basic
case snap(CGFloat)
case attachment(CGFloat,CGFloat)
case gravity(Double)
}
extension UIView: BasicConfigurable, SnapConfigurable, AttachmentConfigurable, GravityConfigurable, StepControllable {
//MARK: animation methods
public func moveX(_ increment: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .moveX(increment))
context.addAnimationType(type)
return self
}
public func moveY(_ increment: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .moveY(increment))
context.addAnimationType(type)
return self
}
public func moveTo(_ point: CGPoint) -> Self {
let type = AnimationType(type: .basic, subType: .moveTo(point))
context.addAnimationType(type)
return self
}
public func makeColor(_ color: UIColor) -> Self {
let type = AnimationType(type: .basic, subType: .color(color))
context.addAnimationType(type)
return self
}
public func makeAlpha(_ alpha: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .alpha(alpha))
context.addAnimationType(type)
return self
}
public func rotate(_ z: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotate(z))
context.addAnimationType(type)
return self
}
public func rotateX(_ x: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotateX(x))
context.addAnimationType(type)
return self
}
public func rotateY(_ y: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotateY(y))
context.addAnimationType(type)
return self
}
public func rotateXY(_ xy: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotateXY(xy))
context.addAnimationType(type)
return self
}
public func makeWidth(_ width: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .width(width))
context.addAnimationType(type)
return self
}
public func makeHeight(_ height: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .height(height))
context.addAnimationType(type)
return self
}
public func makeSize(_ size: CGSize) -> Self {
let type = AnimationType(type: .basic, subType: .size(size))
context.addAnimationType(type)
return self
}
public func makeFrame(_ frame: CGRect) -> Self {
let type = AnimationType(type: .basic, subType: .frame(frame))
context.addAnimationType(type)
return self
}
public func makeBounds(_ bounds: CGRect) -> Self {
let type = AnimationType(type: .basic, subType: .bounds(bounds))
context.addAnimationType(type)
return self
}
public func scaleX(_ x: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .scaleX(x))
context.addAnimationType(type)
return self
}
public func scaleY(_ y: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .scaleY(y))
context.addAnimationType(type)
return self
}
public func scaleXY(_ x: CGFloat, _ y: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .scaleXY(x,y))
context.addAnimationType(type)
return self
}
public func cornerRadius(_ radius: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .cornerRadius(radius))
context.addAnimationType(type)
return self
}
public func borderWidth(_ width: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .borderWidth(width))
context.addAnimationType(type)
return self
}
public func shadowRadius(_ radius: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .shadowRadius(radius))
context.addAnimationType(type)
return self
}
public func zPosition(_ position: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .zPosition(position))
context.addAnimationType(type)
return self
}
public func anchorPoint(_ point: CGPoint) -> Self {
let type = AnimationType(type: .basic, subType: .anchorPoint(point))
context.addAnimationType(type)
return self
}
public func anchorPointZ(_ z: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .anchorPointZ(z))
context.addAnimationType(type)
return self
}
public func shadowOffset(_ offset: CGSize) -> Self {
let type = AnimationType(type: .basic, subType: .shadowOffset(offset))
context.addAnimationType(type)
return self
}
public func shadowColor(_ color: UIColor) -> Self {
let type = AnimationType(type: .basic, subType: .shadowColor(color))
context.addAnimationType(type)
return self
}
public func shadowOpacity(_ opacity: Float) -> Self {
let type = AnimationType(type: .basic, subType: .shadowOpacity(opacity))
context.addAnimationType(type)
return self
}
public func makeTintColor(_ color: UIColor) -> Self {
let type = AnimationType(type: .basic, subType: .tintColor(color))
context.addAnimationType(type)
return self
}
// For UILabel UITextView
public func makeTextColor(color: UIColor) -> Self {
let type = AnimationType(type: .basic, subType: .textColor(color))
context.addAnimationType(type)
return self
}
public func completion(_ c: @escaping () -> Void) -> Self {
context.changeCompletion(c)
return self
}
//MARK: Physical Animation
//Snap
public func snap(_ damping: CGFloat = 0.5) -> Self {
context.changeMainType(.snap(damping))
return self
}
//Attachment
public func attachment(_ damping: CGFloat = 0.5, frequency: CGFloat = 0.5) -> Self {
context.changeMainType(.attachment(damping, frequency))
return self
}
//Gravity
public func gravity(_ magnitude: Double = 1.0) -> Self {
context.changeMainType(.gravity(magnitude))
return self
}
//MARK: Basic Animation configurations
public func duration(_ d: CFTimeInterval) -> Self {
context.changeDuration(d)
return self
}
public func easing(_ type: TimingFunctionType) -> Self {
context.changeEasing(type)
return self
}
public func delay(_ d: CFTimeInterval) -> Self {
context.changeDelay(d)
return self
}
public func reverses() -> Self {
context.changeAutoreverses(true)
return self
}
public func repeatCount(_ count: Int) -> Self {
context.changeRepeatCount(count)
return self
}
//MARK: Chainable methods
public func then() -> Self {
context.makeNextStep()
return self
}
//commit to excute
public func animate() -> Void {
context.commit()
}
//MARK: StepControllable methods
public func cancelAllRemaining() {
context.removeAllRemaining()
}
//Private Context for view and layer
internal var context: AnimationContext {
get {
let identifier = String(describing: Unmanaged.passUnretained(self.layer).toOpaque())
var context = self.layer.value(forKey: identifier) as? AnimationContext
if context == nil {
context = AnimationContext(object: self)
self.layer.setValue(context!, forKey: identifier)
}
return context!
}
}
}
private var AnimationContextIdentifer = "#"
``` | /content/code_sandbox/Sources/UIView+Stellar.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 2,030 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
internal class AnimatorCoordinator: NSObject, UIDynamicAnimatorDelegate {
static let shared = AnimatorCoordinator()
fileprivate var activedAnimators: [UIDynamicAnimator] = Array()
fileprivate var basicAnimator = UIDynamicAnimator()
//MARK: public methods
func addBasicBehavior(_ b: UIDynamicBehavior) {
basicAnimator.addBehavior(b)
}
func addBehavior(_ b: UIDynamicBehavior) {
addBehaviors([b])
}
func addBehaviors(_ behaviors: [UIDynamicBehavior]) {
let animator = activedAnimators.last
for b in behaviors {
if let exsist = animator {
switch b {
case b as UIGravityBehavior:
fallthrough
case b as UICollisionBehavior:
createAnimator(b)
default:
exsist.addBehavior(b)
}
} else {
createAnimator(b)
}
}
}
fileprivate func createAnimator(_ behavior: UIDynamicBehavior) {
let animator = UIDynamicAnimator()
animator.delegate = self
animator.addBehavior(behavior)
activedAnimators.append(animator)
}
//MARK: UIDynamicAnimatorDelegate methods
func dynamicAnimatorDidPause(_ animator: UIDynamicAnimator) {
let index = activedAnimators.firstIndex(of: animator)
activedAnimators.remove(at: index!)
}
func dynamicAnimatorWillResume(_ animator: UIDynamicAnimator) {
//
}
}
``` | /content/code_sandbox/Sources/AnimatorCoordinator.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 518 |
```swift
//
// CALayer+AnimateBehavior.swift
// StellarDemo
//
// Created by AugustRush on 6/21/16.
//
import UIKit
extension CALayer: DriveAnimateBehaviors {
func behavior(forType type: AnimationType, step: AnimationStep) -> UIDynamicBehavior {
let mainType = type.mainType
let subType = type.subType
return createDynamicBehavior(withStyle: mainType, subType: subType, step: step)
}
fileprivate func createDynamicBehavior(withStyle style: AnimationStyle, subType: AnimationSubType, step: AnimationStep) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch subType {
case .moveX(let inc):
let from = self.position.x
let to = from + inc
let render = {(f: CGFloat) in
self.position.x = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .moveY(let inc):
let from = self.position.y
let to = from + inc
let render = {(f: CGFloat) in
self.position.y = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .moveTo(let position):
let from = self.position
let to = position
let render = {(p: CGPoint) in
self.position = p
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .moveXY(let x, let y):
let from = CGPoint.zero
let to = CGPoint(x: x, y: y)
let frame = self.frame
let render = {(p: CGPoint) in
self.frame = frame.offsetBy(dx: p.x, dy: p.y)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .color(let color):
var from = UIColor.clear
if let bc = self.backgroundColor {
from = UIColor(cgColor: bc)
}
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c.cgColor
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .opacity(let o):
let from = self.opacity
let to = o
let render = {(f: Float) in
self.opacity = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .width(let w):
let from = self.bounds.width
let to = w
let render = {(f: CGFloat) in
self.bounds.size.width = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, f, 1, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.transform
let render = {(f: CGFloat) in
self.transform = CATransform3DScale(transform, 1, y, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.transform
let render = {(p: CGPoint) in
self.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .cornerRadius(let r):
let from = self.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.cornerRadius = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .borderWidth(let b):
let from = self.borderWidth
let to = b
let render = {(f: CGFloat) in
self.borderWidth = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowRadius(let s):
let from = self.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.shadowRadius = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .zPosition(let p):
let from = self.zPosition
let to = p
let render = {(f: CGFloat) in
self.zPosition = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .anchorPoint(let point):
let from = self.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.anchorPoint = p
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .anchorPointZ(let z):
let from = self.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.anchorPointZ = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowOffset(let size):
let from = self.shadowOffset
let to = size
let render = {(s: CGSize) in
self.shadowOffset = s
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowColor(let c):
let color = self.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.shadowColor = c.cgColor
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowOpacity(let o):
let from = self.shadowOpacity
let to = o
let render = {(f: Float) in
self.shadowOpacity = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
default:
fatalError("Unsupport this animation type!")
}
return behavior
}
//MARK: Private methods
fileprivate func basicBehavior<T: Interpolatable>(_ step: AnimationStep,from: T, to: T, render: @escaping ((T) -> Void)) -> UIDynamicBehavior {
let item = DynamicItemBasic(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.duration = step.duration
item.timingFunction = step.timing.easing()
item.delay = step.delay
item.repeatCount = step.repeatCount
item.autoreverses = step.autoreverses
return push
}
fileprivate func snapBehavior<T: Interpolatable>(_ damping: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let snap = item.snapBehavior(point, damping: damping)
item.behavior = snap
return snap
}
fileprivate func attachmentBehavior<T: Interpolatable>(_ damping: CGFloat, frequency: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let attachment = item.attachmentBehavior(point, length: 0.0, damping: damping, frequency: frequency)
item.behavior = attachment
return attachment
}
fileprivate func gravityBehavior<T: Interpolatable>(_ magnitude: Double, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItemGravity(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.magnitude = magnitude
return push
}
}
``` | /content/code_sandbox/Sources/CALayer+AnimateBehavior.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 5,209 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol GravityConfigurable: BasicChainable {
func gravity(_ magnitude: Double) -> Self
}
``` | /content/code_sandbox/Sources/GravityConfigurable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 224 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol Chainable {
//Chainable methods
func then() -> Self
func animate() -> Void
}
``` | /content/code_sandbox/Sources/Chainable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 228 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
//for 4 latitude
final class DynamicItem<T: Vectorial>: NSObject, UIDynamicItem {
var from: T
var to: T
var render: (T) -> Void
var complete = false
var boundaryLimit = false
var completion: (() -> Void)?
internal var fromR: Vector4
internal var toR: Vector4
weak var behavior: UIDynamicBehavior!
fileprivate var change: (x: Double,y: Double,z: Double,w: Double)
var referenceChangeLength: Double
init(from: T, to: T, render: @escaping (T) -> Void) {
self.from = from
self.to = to
self.render = render
//
self.fromR = from.reverse()
self.toR = to.reverse()
//
let x = toR.one - fromR.one
let y = toR.two - fromR.two
let z = toR.three - fromR.three
let w = toR.four - fromR.four
self.change = (x,y,z,w)
//
let originChange = sqrt(x*x + y*y)
let sizeChange = sqrt(z*z + w*w)
self.referenceChangeLength = max(originChange, sizeChange)
}
deinit {
self.render(to)
complete = true
completion?()
}
//MARK: Update frame
func updateFrame() {
let yChange = fabs(Double(center.y))
let progress = yChange / referenceChangeLength
let curX = fromR.one + change.x * progress;
let curY = fromR.two + change.y * progress;
let curZ = fromR.three + change.z * progress;
let curW = fromR.four + change.w * progress;
let rect = Vector4.init((curX.isNaN ? 0 : curX,curY.isNaN ? 0 : curY,curZ.isNaN ? 0 : curZ,curW.isNaN ? 0 : curZ))
var curV = from.convert(rect)
if progress >= 1.0 {
if boundaryLimit {
curV = to
behavior.cancel()
complete = true
}
}
self.render(curV)
}
//MARK: UIDynamicItem protocol
var center: CGPoint = CGPoint.zero {
didSet {
updateFrame()
}
}
var transform: CGAffineTransform = CGAffineTransform.identity
var bounds: CGRect {
get {
return CGRect(x: -50.0, y: -50.0, width: 100.0, height: 100.0)
}
}
}
``` | /content/code_sandbox/Sources/DynamicItem.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 785 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
extension Float: Physical {
//Vetorial
public func convert(_ p: Vector4) -> Float {
return Float(p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.two = Double(self)
return vector
}
//Interpolatable
public func interpolate(_ progress: Double, to: Float, externalData: Any?) -> Float {
let change = to - self
return self + change * Float(progress)
}
}
extension Double: Physical {
//Vetorial
public func convert(_ p: Vector4) -> Double {
return p.two
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.two = self
return vector
}
//Interpolatable
public func interpolate(_ progress: Double, to: Double, externalData: Any?) -> Double {
let change = to - self
return self + change * progress
}
}
extension CGFloat: Physical {
public func convert(_ p: Vector4) -> CGFloat {
return CGFloat(p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.two = Double(self)
return vector
}
//Interpolatable
public func interpolate(_ progress: Double, to: CGFloat, externalData: Any?) -> CGFloat {
let change = to - self
return self + change * CGFloat(progress)
}
}
extension CGSize: Physical {
//
public func convert(_ p: Vector4) -> CGSize {
return CGSize(width: p.one, height: p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.one = Double(width)
vector.two = Double(height)
return vector
}
//
public func interpolate(_ progress: Double, to: CGSize, externalData: Any?) -> CGSize {
let wChnaged = to.width - self.width;
let hChanged = to.height - self.height;
let currentW = self.width + wChnaged * CGFloat(progress);
let currentH = self.height + hChanged * CGFloat(progress);
return CGSize(width: currentW, height: currentH)
}
}
extension CGPoint: Physical {
//
public func convert(_ p: Vector4) -> CGPoint {
return CGPoint(x: p.one, y: p.two)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.one = Double(self.x)
vector.two = Double(self.y)
return vector
}
public func interpolate(_ progress: Double, to: CGPoint, externalData: Any?) -> CGPoint {
let xChnaged = to.x - self.x;
let yChanged = to.y - self.y;
let currentX = self.x + xChnaged * CGFloat(progress);
let currentY = self.y + yChanged * CGFloat(progress);
return CGPoint(x: currentX, y: currentY)
}
}
extension CGRect: Physical {
public func convert(_ p: Vector4) -> CGRect {
return CGRect.init(x: p.one, y: p.two, width: p.three, height: p.four)
}
public func reverse() -> Vector4 {
let vector = Vector4()
vector.one = Double(self.origin.x)
vector.two = Double(self.origin.y)
vector.three = Double(self.size.width)
vector.four = Double(self.size.height)
return vector
}
//
public func interpolate(_ progress: Double, to: CGRect, externalData: Any?) -> CGRect {
let xChanged = to.minX - self.minX
let yChanged = to.minY - self.minY
let wChnaged = to.width - self.width;
let hChanged = to.height - self.height;
let currentX = self.minX + xChanged * CGFloat(progress)
let currentY = self.minY + yChanged * CGFloat(progress)
let currentW = self.width + wChnaged * CGFloat(progress)
let currentH = self.height + hChanged * CGFloat(progress)
return CGRect(x: currentX, y: currentY, width: currentW, height: currentH)
}
}
extension UIColor: Physical {
//
public func convert(_ p: Vector4) -> Self {
let hue = p.one / 250.0
let saturation = p.two / 250.0
let brightness = p.three / 250.0
let alpha = p.four / 250.0
return convertT(CGFloat(hue),saturation: CGFloat(saturation),brightness: CGFloat(brightness),alpha: CGFloat(alpha))
}
public func reverse() -> Vector4 {
var hue: CGFloat = 0.0
var saturation: CGFloat = 0.0
var brightness: CGFloat = 0.0
var alpha: CGFloat = 0.0
self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
hue *= 250.0
saturation *= 250.0
brightness *= 250.0
alpha *= 250.0
let vector = Vector4()
vector.one = Double(hue)
vector.two = Double(saturation)
vector.three = Double(brightness)
vector.four = Double(alpha)
return vector
}
fileprivate func convertT<T>(_ hue: CGFloat,saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) -> T {
let color = UIColor(hue: hue,saturation: saturation,brightness: brightness,alpha: alpha)
return unsafeBitCast(color, to: T.self)
}
//
public func interpolate(_ progress: Double, to: UIColor, externalData: Any?) -> Self {
let infos = externalData as! (ColorInfo,ColorInfo)
let fromInfo = infos.0
let toInfo = infos.1
let changedHue = toInfo.hue - fromInfo.hue
let changedSaturation = toInfo.saturation - fromInfo.saturation
let changedBrightness = toInfo.brightness - fromInfo.brightness
let changedAlpha = toInfo.alpha - fromInfo.alpha
let curHue = fromInfo.hue + changedHue * CGFloat(progress)
let curSaturation = fromInfo.saturation + changedSaturation * CGFloat(progress)
let curBrightness = fromInfo.brightness + changedBrightness * CGFloat(progress)
let curAlpha = fromInfo.alpha + changedAlpha * CGFloat(progress)
return convertT(curHue,saturation: curSaturation,brightness: curBrightness,alpha: curAlpha)
}
//performance
typealias ColorInfo = (hue:CGFloat,saturation:CGFloat,brightness:CGFloat,alpha:CGFloat)
internal func colorInfo() -> ColorInfo {
var hue: CGFloat = 0.0
var saturation: CGFloat = 0.0
var brightness: CGFloat = 0.0
var alpha: CGFloat = 0.0
self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return (hue,saturation,brightness,alpha)
}
}
``` | /content/code_sandbox/Sources/Value+Physical.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,781 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol BasicChainable: Chainable {
func moveX(_ increment: CGFloat) -> Self
func moveY(_ increment: CGFloat) -> Self
func moveTo(_ point: CGPoint) -> Self
func makeColor(_ color: UIColor) -> Self
func makeAlpha(_ alpha: CGFloat) -> Self
func rotate(_ z: CGFloat) -> Self
func rotateX(_ x: CGFloat) -> Self
func rotateY(_ y: CGFloat) -> Self
func rotateXY(_ xy: CGFloat) -> Self
func makeWidth(_ width: CGFloat) -> Self
func makeHeight(_ height: CGFloat) -> Self
func makeSize(_ size: CGSize) -> Self
func makeFrame(_ frame: CGRect) -> Self
func makeBounds(_ bounds: CGRect) -> Self
func scaleX(_ x: CGFloat) -> Self
func scaleY(_ y: CGFloat) -> Self
func scaleXY(_ x: CGFloat, _ y: CGFloat) -> Self
func cornerRadius(_ radius: CGFloat) -> Self
func borderWidth(_ width: CGFloat) -> Self
func shadowRadius(_ radius: CGFloat) -> Self
func zPosition(_ position: CGFloat) -> Self
func anchorPoint(_ point: CGPoint) -> Self
func anchorPointZ(_ z: CGFloat) -> Self
func shadowOffset(_ offset: CGSize) -> Self
func shadowColor(_ color: UIColor) -> Self
func shadowOpacity(_ opacity: Float) -> Self
func makeTintColor(_ color: UIColor) -> Self
func completion(_ c: @escaping () -> Void) -> Self
}
``` | /content/code_sandbox/Sources/BasicChainable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 552 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
internal class AnimationContext: NSObject, UIDynamicAnimatorDelegate, AnimationSequenceDelegate {
fileprivate weak var object: DriveAnimateBehaviors!
fileprivate var mutipleSequences = [AnimationSequence]()
//MARK: init method
init(object: DriveAnimateBehaviors) {
self.object = object
}
//MARK: public methods
func addAnimationType(_ type: AnimationType) {
let step = lastStep()
step.types.append(type)
}
func changeDuration(_ d: CFTimeInterval) {
let step = lastStep()
step.duration = d
}
func changeDelay(_ d: CFTimeInterval) {
let step = lastStep()
step.delay = d
}
func changeAutoreverses(_ a: Bool) {
let step = lastStep()
step.autoreverses = a
}
func changeRepeatCount(_ count: Int) {
let step = lastStep()
step.repeatCount = count
}
func changeCompletion(_ c: @escaping () -> Void) {
let step = lastStep()
step.completion = c
}
func changeEasing(_ e: TimingFunctionType) {
let step = lastStep()
step.timing = e
}
func changeMainType(_ type: AnimationStyle) {
let step = lastStep()
let lastAnimationType = step.types.last
guard let _ = lastAnimationType else {
print("You should defined animaton first!")
return
}
lastAnimationType!.mainType = type
}
func makeNextStep() {
let step = AnimationStep()
lastSequence().addStep(step)
}
@discardableResult
func makeNextSequence() -> AnimationSequence {
let sequence = AnimationSequence(object: self.object)
sequence.delegate = self
mutipleSequences.append(sequence)
return sequence
}
func commit() {
//start all sequence
for sequence in mutipleSequences {
sequence.start()
}
//make a temple sequence for next step
makeNextSequence()
}
func removeAllRemaining() {
for sequence in mutipleSequences {
sequence.removeAllSteps()
}
mutipleSequences.removeAll()
}
//MARK: private methods
fileprivate func lastSequence() -> AnimationSequence {
var sequence = mutipleSequences.last
if sequence == nil {
sequence = makeNextSequence()
}
return sequence!
}
fileprivate func lastStep() -> AnimationStep {
let sequence = lastSequence()
var step = sequence.last()
if step == nil {
step = AnimationStep()
sequence.addStep(step!)
}
return step!
}
//MARK: AnimationSequenceDelegate methods
func animationSequenceDidComplete(_ sequence: AnimationSequence) {
let index = mutipleSequences.firstIndex(of: sequence)
if index != nil {
mutipleSequences.remove(at: index!)
}
}
}
``` | /content/code_sandbox/Sources/AnimationContext.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 852 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
class DynamicItemGravity<T: Interpolatable>: NSObject, UIDynamicItem {
var from: T!
var to: T!
var magnitude = 1.0
var render: (T) -> Void
var completion: (() -> Void)?
var boundary = true
weak var behavior: UIDynamicBehavior?
//private vars
fileprivate var referenceChangedLength: Double = 0.0
//External data to store (performance)
fileprivate var externalData: Any?
fileprivate lazy var beginTime = {
return CACurrentMediaTime()
}()
//MARK: init method
init(from: T, to: T, render: @escaping (T) -> Void) {
self.from = from
self.to = to
self.render = render
super.init()
caculateReferenceChangedLength()
}
deinit {
self.completion?()
}
//MARK: private methods
fileprivate func caculateReferenceChangedLength() {
switch from {
case let f as CGFloat:
let t = to as! CGFloat
referenceChangedLength = Double(abs(t - f))
case let f as Float:
let t = to as! Float
referenceChangedLength = Double(abs(t - f))
case let f as Double:
let t = to as! Double
referenceChangedLength = abs(t - f)
case let f as CGSize:
let t = to as! CGSize
let w = abs(t.width - f.width)
let h = abs(t.height - f.height)
referenceChangedLength = max(Double(w), Double(h))
case let f as CGPoint:
let t = to as! CGPoint
let x = abs(t.x - f.x)
let y = abs(t.y - f.y)
referenceChangedLength = max(Double(x), Double(y))
case let f as CGRect:
let t = to as! CGRect
let xChange = abs(t.minX - f.minX)
let yChange = abs(t.minY - f.minY)
let wChange = abs(t.width - f.width)
let hChange = abs(t.height - f.height)
let originC = hypot(xChange, yChange)
let sizeC = hypot(wChange, hChange)
referenceChangedLength = max(Double(originC), Double(sizeC))
case let f as UIColor:
let t = to as! UIColor
let fromInfo = f.colorInfo()
let toInfo = t.colorInfo()
let hueChange = abs(toInfo.hue - fromInfo.hue)
let brightnessChange = abs(toInfo.brightness - fromInfo.brightness)
let saturationChange = abs(toInfo.saturation - fromInfo.saturation)
let alphaChange = abs(toInfo.alpha - fromInfo.alpha)
let oneC = hypot(hueChange, saturationChange) * 1000.0
let twoC = hypot(brightnessChange, alphaChange) * 1000.0
referenceChangedLength = max(Double(oneC), Double(twoC))
externalData = (fromInfo,toInfo)
default:
referenceChangedLength = 1000.0
}
}
fileprivate func updateFrame() {
if referenceChangedLength <= 0.0 {
behavior?.cancel()
return
}
var currentTime = CACurrentMediaTime() - beginTime
currentTime = max(0.0, currentTime)
let offset = gravityOffset(currentTime)
var progress = offset / referenceChangedLength
if progress >= 1.0 {
if boundary {
progress = 1.0
behavior?.cancel()
}
}
let value = from.interpolate(progress, to: to, externalData: externalData)
render(value)
}
fileprivate func gravityOffset(_ t: CFTimeInterval) -> Double {
return t * t * 1000.0 * magnitude;
}
//MARK: UIDynamicItem protocol
var center: CGPoint = CGPoint.zero {
didSet {
updateFrame()
}
}
var transform: CGAffineTransform = CGAffineTransform.identity
var bounds: CGRect {
get {
return CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)
}
}
}
``` | /content/code_sandbox/Sources/DynamicItemGravity.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,142 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
enum AnimationSubType {
case moveX(CGFloat)
case moveY(CGFloat)
case moveXY(CGFloat,CGFloat)//Layer
case moveTo(CGPoint)
case color(UIColor)
case alpha(CGFloat)
case opacity(Float)//Layer
case rotateX(CGFloat)
case rotateY(CGFloat)
case rotate(CGFloat)
case rotateXY(CGFloat)
case width(CGFloat)
case height(CGFloat)
case size(CGSize)
case frame(CGRect)
case bounds(CGRect)
case scaleX(CGFloat)
case scaleY(CGFloat)
case scaleXY(CGFloat,CGFloat)
case cornerRadius(CGFloat)
case borderWidth(CGFloat)
case shadowRadius(CGFloat)
case zPosition(CGFloat)
case anchorPoint(CGPoint)
case anchorPointZ(CGFloat)
case shadowOffset(CGSize)
case shadowColor(UIColor)
case shadowOpacity(Float)
case tintColor(UIColor)
// UILabel,UITextView...
case textColor(UIColor)
}
//temp record for animation type
internal class AnimationType {
var mainType: AnimationStyle
var subType: AnimationSubType
init (type: AnimationStyle, subType: AnimationSubType) {
self.mainType = type
self.subType = subType
}
}
``` | /content/code_sandbox/Sources/AnimationType.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 481 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol BasicConfigurable: BasicChainable {
func duration(_ d: CFTimeInterval) -> Self
func easing(_ type: TimingFunctionType) -> Self
func delay(_ d: CFTimeInterval) -> Self
func reverses() -> Self
func repeatCount(_ count: Int) -> Self
}
``` | /content/code_sandbox/Sources/BasicConfigurable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 270 |
```swift
//
// UIView+AnimateBehavior.swift
// StellarDemo
//
// Created by AugustRush on 6/21/16.
//
import UIKit
extension UIView: DriveAnimateBehaviors {
func behavior(forType type: AnimationType, step: AnimationStep) -> UIDynamicBehavior {
let mainType = type.mainType
let subType = type.subType
return createDynamicBehavior(withStyle: mainType, subType: subType, step: step)
}
//MARK: Basic
fileprivate func createDynamicBehavior(withStyle style: AnimationStyle, subType: AnimationSubType, step: AnimationStep) -> UIDynamicBehavior {
var behavior: UIDynamicBehavior!
switch subType {
case .moveX(let inc):
let from = self.center.x
let to = from + inc
let render = {(f: CGFloat) in
self.center.x = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .moveY(let inc):
let from = self.center.y
let to = from + inc
let render = {(f: CGFloat) in
self.center.y = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .moveTo(let point):
let from = self.center
let to = point
let render = {(p: CGPoint) in
self.center = p
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .color(let color):
let from = self.backgroundColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.backgroundColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .opacity(let o):
let from = self.layer.opacity
let to = o
let render = {(o: Float) in
self.layer.opacity = o
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .alpha(let a):
let from = self.alpha
let to = a
let render = {(f: CGFloat) in
self.alpha = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateX(let x):
let from: CGFloat = 0.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 0, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateY(let y):
let from: CGFloat = 0.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 1, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotate(let z):
let from: CGFloat = 0.0
let to = z
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 0, 0, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .rotateXY(let xy):
let from: CGFloat = 0.0
let to = xy
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DRotate(transform, f, 1, 1, 0)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .width(let w):
let from = self.frame.width
let to = w
let render = {(f: CGFloat) in
self.frame.size.width = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .height(let h):
let from = self.bounds.height
let to = h
let render = {(f: CGFloat) in
self.bounds.size.height = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .size(let size):
let from = self.bounds.size
let to = size
let render = {(s: CGSize) in
self.bounds.size = s
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .frame(let frame):
let from = self.frame
let to = frame
let render = {(f: CGRect) in
self.frame = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .bounds(let frame):
let from = self.bounds
let to = frame
let render = {(f: CGRect) in
self.bounds = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleX(let x):
let from: CGFloat = 1.0
let to = x
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, f, 1, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleY(let y):
let from: CGFloat = 1.0
let to = y
let transform = self.layer.transform
let render = {(f: CGFloat) in
self.layer.transform = CATransform3DScale(transform, 1, y, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .scaleXY(let x, let y):
let from = CGPoint(x: 1, y: 1)
let to = CGPoint(x: x, y: y)
let transform = self.layer.transform
let render = {(p: CGPoint) in
self.layer.transform = CATransform3DScale(transform, p.x, p.y, 1)
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .cornerRadius(let r):
let from = self.layer.cornerRadius
let to = r
let render = {(f: CGFloat) in
self.layer.cornerRadius = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .borderWidth(let b):
let from = self.layer.borderWidth
let to = b
let render = {(f: CGFloat) in
self.layer.borderWidth = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowRadius(let s):
let from = self.layer.shadowRadius
let to = s
let render = {(f: CGFloat) in
self.layer.shadowRadius = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .zPosition(let p):
let from = self.layer.zPosition
let to = p
let render = {(f: CGFloat) in
self.layer.zPosition = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .anchorPoint(let point):
let from = self.layer.anchorPoint
let to = point
let render = {(p: CGPoint) in
self.layer.anchorPoint = p
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .anchorPointZ(let z):
let from = self.layer.anchorPointZ
let to = z
let render = {(f: CGFloat) in
self.layer.anchorPointZ = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowOffset(let size):
let from = self.layer.shadowOffset
let to = size
let render = {(s: CGSize) in
self.layer.shadowOffset = s
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowColor(let c):
let color = self.layer.shadowColor
let from = (color != nil) ? UIColor(cgColor: color!) : UIColor.clear
let to = c
let render = {(c: UIColor) in
self.layer.shadowColor = c.cgColor
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .shadowOpacity(let o):
let from = self.layer.shadowOpacity
let to = o
let render = {(f: Float) in
self.layer.shadowOpacity = f
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .tintColor(let color):
let from = self.tintColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
self.tintColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case .textColor(let color):
switch self {
case let label as UILabel:
let from = label.textColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
label.textColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
case let textView as UITextView:
let from = textView.textColor ?? UIColor.clear
let to = color
let render = {(c: UIColor) in
textView.textColor = c
}
switch style {
case .basic:
behavior = basicBehavior(step, from: from, to: to, render: render)
case .attachment(let damping, let frequency):
behavior = attachmentBehavior(damping, frequency: frequency, from: from, to: to, render: render)
case .gravity(let magnitude):
behavior = gravityBehavior(magnitude, from: from, to: to, render: render)
case .snap(let damping):
behavior = snapBehavior(damping, from: from, to: to, render: render)
}
default:
fatalError("This object has not textColor property!")
}
default:
fatalError("Unsupport this animation type!")
}
return behavior
}
//MARK: Private methods
fileprivate func basicBehavior<T: Interpolatable>(_ step: AnimationStep,from: T, to: T, render: @escaping ((T) -> Void)) -> UIDynamicBehavior {
let item = DynamicItemBasic(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.duration = step.duration
item.timingFunction = step.timing.easing()
item.delay = step.delay
item.repeatCount = step.repeatCount
item.autoreverses = step.autoreverses
return push
}
fileprivate func snapBehavior<T: Vectorial>(_ damping: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let snap = item.snapBehavior(point, damping: damping)
item.behavior = snap
return snap
}
fileprivate func attachmentBehavior<T: Vectorial>(_ damping: CGFloat, frequency: CGFloat, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItem(from: from, to: to, render: render)
let point = CGPoint(x: 0.0, y: item.referenceChangeLength)
let attachment = item.attachmentBehavior(point, length: 0.0, damping: damping, frequency: frequency)
item.behavior = attachment
return attachment
}
fileprivate func gravityBehavior<T: Interpolatable>(_ magnitude: Double, from: T, to: T, render: @escaping (T) -> Void) -> UIDynamicBehavior {
let item = DynamicItemGravity(from: from, to: to, render: render)
let push = item.pushBehavior(.down)
item.behavior = push
item.magnitude = magnitude
return push
}
}
``` | /content/code_sandbox/Sources/UIView+AnimateBehavior.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 5,707 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
enum PhysicalDirection {
case left
case right
case up
case down
case Angle(CGFloat)
case vector(CGFloat,CGFloat)
func angle() -> CGFloat {
switch self {
case .Angle(let a):
return a
case .vector(let x, let y):
return atan2(y, x)
case .left:
return atan2(0, -1)
case .right:
return atan2(0, 1)
case .up:
return atan2(-1, 0)
case .down:
return atan2(1, 0)
}
}
}
extension UIDynamicItem {
//gravity
func gravityBehavior(_ magnitude: CGFloat = 1.0, direction: PhysicalDirection = .down) -> UIGravityBehavior {
let gravity = UIGravityBehavior()
switch direction {
case .Angle(let a):
gravity.setAngle(a, magnitude: magnitude)
case .left:
gravity.gravityDirection = CGVector(dx: -1, dy: 0)
case .right:
gravity.gravityDirection = CGVector(dx: 1, dy: 0)
case .up:
gravity.gravityDirection = CGVector(dx: 0, dy: -1)
case .down:
gravity.gravityDirection = CGVector(dx: 0, dy: 1)
case .vector(let x, let y):
gravity.gravityDirection = CGVector(dx: x, dy: y)
}
gravity.magnitude = magnitude
gravity.addItem(self)
return gravity
}
//snap
func snapBehavior(_ toPoint: CGPoint, damping: CGFloat = 0.5) -> UISnapBehavior {
let snap = UISnapBehavior(item: self,snapTo: toPoint)
snap.damping = damping
return snap
}
//attachment
func attachmentBehavior(_ toAnchor: CGPoint, length: CGFloat = 0.0, damping: CGFloat = 0.5, frequency: CGFloat = 1.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedToAnchor: toAnchor)
attachment.length = length
attachment.damping = damping
attachment.frequency = frequency
return attachment
}
func attachmentBehavior(_ toItem: UIDynamicItem, damping: CGFloat = 0.5, frequency: CGFloat = 1.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedTo: toItem)
attachment.damping = damping
attachment.frequency = frequency
return attachment
}
func attachmentBehavior(_ toItem: UIDynamicItem, damping: CGFloat = 0.5, frequency: CGFloat = 1.0, length: CGFloat = 0.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedTo: toItem)
attachment.damping = damping
attachment.length = length
attachment.frequency = frequency
return attachment
}
//push
func pushBehavior(_ direction: CGVector, mode:UIPushBehavior.Mode = .instantaneous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
push.pushDirection = direction
push.magnitude = magnitude
return push
}
func pushBehavior(_ direction: PhysicalDirection, mode:UIPushBehavior.Mode = .continuous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
switch direction {
case .Angle(let a):
push.setAngle(a, magnitude: magnitude)
case .left:
push.pushDirection = CGVector(dx: -1, dy: 0)
case .right:
push.pushDirection = CGVector(dx: 1, dy: 0)
case .up:
push.pushDirection = CGVector(dx: 0, dy: -1)
case .down:
push.pushDirection = CGVector(dx: 0, dy: 1)
case .vector(let x, let y):
push.pushDirection = CGVector(dx: x, dy: y)
}
push.magnitude = magnitude
return push
}
func pushBehavior(_ angle: CGFloat, mode:UIPushBehavior.Mode = .instantaneous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
push.angle = angle
push.magnitude = magnitude
return push
}
//collision
func collisionBehavior(_ mode: UICollisionBehavior.Mode = .boundaries) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
collision.addItem(self)
return collision
}
func collisionBehavior(_ mode: UICollisionBehavior.Mode = .boundaries, path: UIBezierPath) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
collision.addBoundary(withIdentifier: identifier as NSCopying, for: path)
collision.addItem(self)
return collision
}
func collisionBehavior(_ mode: UICollisionBehavior.Mode = .boundaries, fromPoint: CGPoint, toPoint: CGPoint) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
collision.addBoundary(withIdentifier: identifier as NSCopying, from: fromPoint, to: toPoint)
collision.addItem(self)
return collision
}
//itemBehavior
func itemBehavior(_ elasticity: CGFloat = 0.5, friction: CGFloat = 0.5, density: CGFloat = 1, resistance: CGFloat = 0, angularResistance: CGFloat = 0, allowsRotation: Bool = true) -> UIDynamicItemBehavior {
let behavior = UIDynamicItemBehavior()
behavior.addItem(self)
behavior.elasticity = elasticity
behavior.friction = friction
behavior.density = density
behavior.resistance = resistance
behavior.angularResistance = angularResistance
behavior.allowsRotation = allowsRotation
return behavior
}
}
``` | /content/code_sandbox/Sources/DynamicItem+Behavior.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,567 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol SnapConfigurable: BasicChainable {
func snap(_ damping: CGFloat) -> Self
}
``` | /content/code_sandbox/Sources/SnapConfigurable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 224 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
extension CALayer: BasicConfigurable, SnapConfigurable, AttachmentConfigurable, GravityConfigurable, StepControllable {
//MARK: animation methods
public func moveX(_ increment: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .moveX(increment))
context.addAnimationType(type)
return self
}
public func moveY(_ increment: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .moveY(increment))
context.addAnimationType(type)
return self
}
public func moveTo(_ point: CGPoint) -> Self {
let type = AnimationType(type: .basic, subType: .moveTo(point))
context.addAnimationType(type)
return self
}
public func makeColor(_ color: UIColor) -> Self {
let type = AnimationType(type: .basic, subType: .color(color))
context.addAnimationType(type)
return self
}
public func makeOpacity(_ opacity: Float) -> Self {
let type = AnimationType(type: .basic, subType: .opacity(opacity))
context.addAnimationType(type)
return self
}
public func makeAlpha(_ alpha: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .opacity(Float(alpha)))
context.addAnimationType(type)
return self
}
public func rotate(_ z: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotate(z))
context.addAnimationType(type)
return self
}
public func rotateX(_ x: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotateX(x))
context.addAnimationType(type)
return self
}
public func rotateY(_ y: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotateY(y))
context.addAnimationType(type)
return self
}
public func rotateXY(_ xy: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .rotateXY(xy))
context.addAnimationType(type)
return self
}
public func makeWidth(_ width: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .width(width))
context.addAnimationType(type)
return self
}
public func makeHeight(_ height: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .height(height))
context.addAnimationType(type)
return self
}
public func makeSize(_ size: CGSize) -> Self {
let type = AnimationType(type: .basic, subType: .size(size))
context.addAnimationType(type)
return self
}
public func makeFrame(_ frame: CGRect) -> Self {
let type = AnimationType(type: .basic, subType: .frame(frame))
context.addAnimationType(type)
return self
}
public func makeBounds(_ bounds: CGRect) -> Self {
let type = AnimationType(type: .basic, subType: .bounds(bounds))
context.addAnimationType(type)
return self
}
public func scaleX(_ x: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .scaleX(x))
context.addAnimationType(type)
return self
}
public func scaleY(_ y: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .scaleY(y))
context.addAnimationType(type)
return self
}
public func scaleXY(_ x: CGFloat, _ y: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .scaleXY(x,y))
context.addAnimationType(type)
return self
}
public func cornerRadius(_ radius: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .cornerRadius(radius))
context.addAnimationType(type)
return self
}
public func borderWidth(_ width: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .borderWidth(width))
context.addAnimationType(type)
return self
}
public func shadowRadius(_ radius: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .shadowRadius(radius))
context.addAnimationType(type)
return self
}
public func zPosition(_ position: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .zPosition(position))
context.addAnimationType(type)
return self
}
public func anchorPoint(_ point: CGPoint) -> Self {
let type = AnimationType(type: .basic, subType: .anchorPoint(point))
context.addAnimationType(type)
return self
}
public func anchorPointZ(_ z: CGFloat) -> Self {
let type = AnimationType(type: .basic, subType: .anchorPointZ(z))
context.addAnimationType(type)
return self
}
public func shadowOffset(_ offset: CGSize) -> Self {
let type = AnimationType(type: .basic, subType: .shadowOffset(offset))
context.addAnimationType(type)
return self
}
public func shadowColor(_ color: UIColor) -> Self {
let type = AnimationType(type: .basic, subType: .shadowColor(color))
context.addAnimationType(type)
return self
}
public func shadowOpacity(_ opacity: Float) -> Self {
let type = AnimationType(type: .basic, subType: .shadowOpacity(opacity))
context.addAnimationType(type)
return self
}
public func makeTintColor(_ color: UIColor) -> Self {
let type = AnimationType(type: .basic, subType: .tintColor(color))
context.addAnimationType(type)
return self
}
public func completion(_ c: @escaping () -> Void) -> Self {
context.changeCompletion(c)
return self
}
//MARK: Physical Animation
//Snap
public func snap(_ damping: CGFloat = 0.5) -> Self {
context.changeMainType(.snap(damping))
return self
}
//Attachment
public func attachment(_ damping: CGFloat = 0.5, frequency: CGFloat = 0.5) -> Self {
context.changeMainType(.attachment(damping, frequency))
return self
}
//Gravity
public func gravity(_ magnitude: Double = 1.0) -> Self {
context.changeMainType(.gravity(magnitude))
return self
}
//MARK: Basic Animation configurations
public func duration(_ d: CFTimeInterval) -> Self {
context.changeDuration(d)
return self
}
public func easing(_ type: TimingFunctionType) -> Self {
context.changeEasing(type)
return self
}
public func delay(_ d: CFTimeInterval) -> Self {
context.changeDelay(d)
return self
}
public func reverses() -> Self {
context.changeAutoreverses(true)
return self
}
public func repeatCount(_ count: Int) -> Self {
context.changeRepeatCount(count)
return self
}
//MARK: Chainable methods
public func then() -> Self {
context.makeNextStep()
return self
}
//commit to excute
public func animate() -> Void {
context.commit()
}
//MARK: StepControllable methods
public func cancelAllRemaining() {
context.removeAllRemaining()
}
//Private Context for view and layer
fileprivate var context: AnimationContext {
get {
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
var context = self.value(forKey: identifier) as? AnimationContext
if context == nil {
context = AnimationContext(object: self)
self.setValue(context!, forKey: identifier)
}
return context!
}
}
}
``` | /content/code_sandbox/Sources/CALayer+Stellar.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,985 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
public protocol AttachmentConfigurable: BasicChainable {
func attachment(_ damping: CGFloat, frequency: CGFloat) -> Self
}
``` | /content/code_sandbox/Sources/AttachmentConfigurable.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 228 |
```swift
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
/// A set of preset bezier curves.
public enum TimingFunctionType {
/// Equivalent to `kCAMediaTimingFunctionDefault`.
case `default`
/// Equivalent to `kCAMediaTimingFunctionEaseIn`.
case easeIn
/// Equivalent to `kCAMediaTimingFunctionEaseOut`.
case easeOut
/// Equivalent to `kCAMediaTimingFunctionEaseInEaseOut`.
case easeInEaseOut
/// No easing.
case linear
/// Inspired by the default curve in Google Material Design.
case swiftOut
///
case backEaseIn
///
case backEaseOut
///
case backEaseInOut
///
case bounceOut
///
case sine
///
case circ
///
case exponentialIn
///
case exponentialOut
///
case elasticIn
///
case bounceReverse
///
case elasticOut
/// custom
case custom(Double, Double, Double, Double)
func easing() -> TimingSolvable {
switch self {
case .default:
return UnitBezier(p1x: 0.25, p1y: 0.1, p2x: 0.25, p2y: 1.0)
case .easeIn:
return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 1.0, p2y: 1.0)
case .easeOut:
return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 0.58, p2y: 1.0)
case .easeInEaseOut:
return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 0.58, p2y: 1.0)
case .linear:
return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 1.0, p2y: 1.0)
case .swiftOut:
return UnitBezier(p1x: 0.4, p1y: 0.0, p2x: 0.2, p2y: 1.0)
case .backEaseIn:
return EasingContainer(easing: { (t: Double) in
return t * t * t - t * sin(t * .pi)
})
case .backEaseOut:
return EasingContainer(easing: { (t: Double) in
let f = (1 - t);
return 1 - (f * f * f - f * sin(f * .pi));
})
case .backEaseInOut:
return EasingContainer(easing: { (t: Double) in
if(t < 0.5) {
let f = 2 * t;
return 0.5 * (f * f * f - f * sin(f * .pi));
} else {
let f = (1.0 - (2.0 * t - 1.0));
let cubic = f * f * f
return 0.5 * (1.0 - (cubic - f * sin(f * .pi))) + 0.5;
}
})
case .bounceOut:
return EasingContainer(easing: { (t: Double) in
if(t < 4/11.0){
return (121 * t * t)/16.0;
} else if(t < 8/11.0){
return (363/40.0 * t * t) - (99/10.0 * t) + 17/5.0;
}else if(t < 9/10.0){
return (4356/361.0 * t * t) - (35442/1805.0 * t) + 16061/1805.0;
}else{
return (54/5.0 * t * t) - (513/25.0 * t) + 268/25.0;
}
})
case .sine:
return EasingContainer(easing: { (t: Double) in
return 1 - cos( t * .pi / 2.0)
})
case .circ:
return EasingContainer(easing: { (t: Double) in
return 1 - sqrt( 1.0 - t * t )
})
case .exponentialIn:
return EasingContainer(easing: { (t: Double) in
return (t == 0.0) ? t : pow(2, 10 * (t - 1))
})
case .exponentialOut:
return EasingContainer(easing: { (t: Double) in
return (t == 1.0) ? t : 1 - pow(2, -10 * t)
})
case .elasticIn:
return EasingContainer(easing: { (t: Double) in
return sin(13.0 * (.pi / 2.0) * t) * pow(2, 10 * (t - 1))
})
case .elasticOut:
return EasingContainer(easing: { (t: Double) in
return sin(-13.0 * (.pi / 2.0) * (t + 1)) * pow(2, -10 * t) + 1.0;
})
case .bounceReverse:
return EasingContainer(easing: { (t: Double) in
var bounce: Double = 4.0
var pow2 = 0.0
repeat {
bounce = bounce - 1.0
pow2 = pow(2, bounce)
} while (t < (pow2 - 1.0 ) / 11.0)
return 1 / pow( 4, 3 - bounce ) - 7.5625 * pow( ( pow2 * 3 - 2 ) / 22 - t, 2 );
})
case .custom(let p1x,let p1y,let p2x,let p2y):
return UnitBezier(p1x: p1x, p1y: p1y, p2x: p2x, p2y: p2y)
}
}
}
class EasingContainer: TimingSolvable {
let easing: (Double) -> Double
init(easing: @escaping (Double) -> Double) {
self.easing = easing
}
//
func solveOn(_ time: Double, epslion: Double) -> Double {
return self.easing(time)
}
}
``` | /content/code_sandbox/Sources/TimingFunction.swift | swift | 2016-05-25T09:02:36 | 2024-08-14T16:00:58 | Stellar | AugustRush/Stellar | 2,933 | 1,679 |
```powershell
param
(
[switch]
$Create,
[string[]]
$Module = @('AutomatedLabUnattended' # Careful... This is also the import order!
'AutomatedLabTest',
'PSLog',
'PSFileTransfer',
'AutomatedLabDefinition',
'AutomatedLabWorker',
'HostsFile',
'AutomatedLabNotifications',
'AutomatedLabCore',
'AutomatedLab.Recipe')
)
$buildFolder = if ($env:APPVEYOR_BUILD_FOLDER) { $env:APPVEYOR_BUILD_FOLDER } else { $PSScriptRoot }
$outPath = foreach ($moduleName in $Module)
{
$outputFolder = Join-Path $buildFolder -ChildPath "Help/$moduleName/en-us"
$outputFolder
Import-Module (Join-Path $buildFolder "publish/$moduleName") -Force
if ($Create.IsPresent)
{
$null = New-MarkdownHelp -Module $moduleName -WithModulePage -OutputFolder $outputFolder -Force -AlphabeticParamsOrder
}
}
if (-not $Create.IsPresent)
{
Update-MarkdownHelpModule -Path $outPath -RefreshModulePage -AlphabeticParamsOrder
}
foreach ($md in (Get-ChildItem -Filter *.md -Recurse -Path (Join-Path -Path $buildFolder -ChildPath Help)))
{
if (-not (Get-Command -ErrorAction SilentlyContinue -Name $md.BaseName)) { continue }
$content = Get-Content -Raw -Path $md.FullName
$moduleName = $md.Directory.Parent.Name
$url = [System.Uri]::EscapeUriString(('path_to_url{0}/en-us/{1}' -f $moduleName, $md.BaseName))
$content = $content -replace 'online version:.*', "online version: $url"
$content | Set-Content -Path $md.FullName
}
$mkdocs = Join-Path -Path $buildFolder -ChildPath mkdocs.yml -Resolve -ErrorAction Stop
$mkdocsContent = Get-Content -Raw -Path $mkdocs | ConvertFrom-Yaml
# Update Sample Scripts help content
$null = ($mkdocsContent.nav | Where-Object {$_.Keys -contains 'Sample scripts'})['Sample scripts'] = New-Object System.Collections.ArrayList
foreach ($folder in (Get-ChildItem -Path (Join-Path -Path $buildFolder -ChildPath 'LabSources\SampleScripts') -Directory))
{
$folderObject = @{ $folder.Name = New-Object System.Collections.ArrayList}
foreach ($sample in $folder.GetFiles('*.ps1'))
{
$mdRelativePathMkDocs = "Wiki/SampleScripts/$($folder.BaseName)/en-us/$($sample.BaseName).md"
$mdRelativePath = "Help/Wiki/SampleScripts/$($folder.BaseName)/en-us/$($sample.BaseName).md"
$mdFullPath = Join-Path -Path $buildFolder -ChildPath $mdRelativePath
$scriptObject = @{
$sample.Name = $mdRelativePathMkDocs
}
$null = $folderObject[$folder.BaseName].Add($scriptObject)
if (Test-Path -Path $mdFullPath) { continue }
if (-not (Test-Path -Path (Split-Path -Path $mdFullPath -Parent) ))
{
$null = New-Item -ItemType Directory -Path (Split-Path -Path $mdFullPath -Parent)
}
$mdContent = @"
# $($folder.Name) - $($sample.BaseName)
INSERT TEXT HERE
``````powershell
$(Get-Content -Raw -Path $sample.FullName)
``````
"@
$mdContent | Set-Content -Path $mdFullPath
}
$null = ($mkdocsContent.nav | Where-Object {$_.Keys -contains 'Sample scripts'})['Sample scripts'].Add($folderObject)
}
# Update mkdocs.yml as part of a new help commit
$null = ($mkdocsContent.nav | Where-Object {$_.Keys -contains 'Module help'})['Module help'] = New-Object System.Collections.ArrayList
$commands = Get-Command -Module $Module | Sort-Object Name -Unique
foreach ($command in $commands)
{
$null = ($mkdocsContent.nav | Where-Object {$_.Keys -contains 'Module help'})['Module help'].Add(@{
$command.Name = "$($command.Module.Name)/en-us/$($command.Name).md"
})
}
$mkdocsContent | ConvertTo-Yaml -OutFile $mkdocs -Force
``` | /content/code_sandbox/NewOrUpdateHelp.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 991 |
```yaml
version: 5.54.{build}
image:
- Visual Studio 2022
- Ubuntu2004
environment:
AppVeyorApi:
secure: e9BtF4uHDk3PxumsQHVK6I5GXlIh0IN2Gq1BBetSJx8=
NuGetApiKey:
secure: tAdUQmRiZ270LOPN8SwbjISLfu6ldDTw6LWvdtsk+pQR7r5bJnGrG8Ntyt87edJ/
AzureServicePrincipal:
secure: Kk48Oy97Tk9Ap9F9/2wbBSaFG/TDgJgpCnUduc9fR8cNq/t75PzvjTdrLDCW86YiaHTHWClx5ePCdLhwAWCGS7YG8fh/sPZBjKpbNpoaM0iFkCtWfEhjWNZv7dg6pvLaZzcY7hAmH5Wp/JkPMlqVmCo2seJUAe6RI94765L8lhhBMXuSm54o0yUPxfq/gwp/kpGixKJioWUfvK7dFvCakT70JTFjcWILv7I2LzrtohDLnU+FeAXcx8ypEUvYnqJArLNlKrgz2TpZ3FMqm7PzgQAodsgPYR/Vtn3E5AsQwJAcsfYzYNxjwEp/lkXs2ik66o1gxg0oHo5qzPmfCtNTyCdjJRleRdKWLKejRM2W3tpEsQYz+your_sha256_hash9apQRLAxZ91JbClPgirRld1pswZSyXR8wtRVFSOtcJ9/T/HsNULTq9uLVlGXMw3oDyBm8k1ij+ENLPm # JHPs Dingen your_sha256_hashF4f3SfhS+your_sha256_hashyour_sha256_hashyour_sha256_hashiOa31zO4MAOGJ1pVHQrazuchwMXTu8q2SozNmV1ZOZGtVcy7ZAKfD/your_sha256_hashBbKl6exgBiA2jW6uBwEA9AJIwqLphorbmAF8gwhBk3U1nt4mxGK/XzI/hkCnF9mkgysMg78MO59CRsn+8axt4e+SjECcPzyOfqwj/0RkFcP8hv/PdFxBRp05+J+/ZlSPV
#environment:
# AzureServicePrincipal:
# secure: your_sha256_hashF4f3SfhS+your_sha256_hashyour_sha256_hashyour_sha256_hashiOa31zO4MAOGJ1pVHQrazuchwMXTu8q2SozNmV1ZOZGtVcy7ZAKfD/your_sha256_hashBbKl6exgBiA2jW6uBwEA9AJIwqLphorbmAF8gwhBk3U1nt4mxGK/XzI/hkCnF9mkgysMg78MO59CRsn+8axt4e+SjECcPzyOfqwj/0RkFcP8hv/PdFxBRp05+J+/ZlSPV
branches:
except:
- /(?i).*release.*/
skip_tags: true
dotnet_csproj:
patch: true
file: '**\LabXml.csproj'
version: "{version}"
package_version: "{version}"
assembly_version: "{version}"
file_version: "{version}"
informational_version: "{version}"
assembly_info:
patch: true
file: AssemblyInfo.*
assembly_version: "{version}"
assembly_file_version: "{version}"
assembly_informational_version: "{version}"
before_build:
- ps: "& $env:APPVEYOR_BUILD_FOLDER/.build/01-prerequisites.ps1"
build_script:
- ps: "& $env:APPVEYOR_BUILD_FOLDER/.build/02-build.ps1"
- ps: "& $env:APPVEYOR_BUILD_FOLDER/.build/03-validate.ps1"
for:
- matrix:
only:
- image: Visual Studio 2022
deploy:
- provider: GitHub
description: "This is an automated deployment"
auth_token:
secure: HsE6rIUR/bsL7wBhrBgfFf3HFDkiqASb96bKgW34XOZVjLUYVIq/yFAVs1a5Ydxy # your encrypted token from GitHub
artifact: alinstaller
draft: false
force_update: true
prerelease: false
on:
branch: master
- provider: GitHub
description: "This is an automated prerelease deployment"
auth_token:
secure: HsE6rIUR/bsL7wBhrBgfFf3HFDkiqASb96bKgW34XOZVjLUYVIq/yFAVs1a5Ydxy # your encrypted token from GitHub
artifact: alinstaller
draft: false
force_update: true
prerelease: true
on:
branch: develop
- matrix:
only:
- image: Ubuntu2004
deploy:
- provider: GitHub
description: "This is an automated deployment"
auth_token:
secure: HsE6rIUR/bsL7wBhrBgfFf3HFDkiqASb96bKgW34XOZVjLUYVIq/yFAVs1a5Ydxy # your encrypted token from GitHub
artifact: aldebianpackage
draft: false
force_update: true
prerelease: false
on:
branch: master
- provider: GitHub
description: "This is an automated deployment"
auth_token:
secure: HsE6rIUR/bsL7wBhrBgfFf3HFDkiqASb96bKgW34XOZVjLUYVIq/yFAVs1a5Ydxy # your encrypted token from GitHub
artifact: alrpmpackage
draft: false
force_update: true
prerelease: false
on:
branch: master
- provider: GitHub
description: "This is an automated prerelease deployment"
auth_token:
secure: HsE6rIUR/bsL7wBhrBgfFf3HFDkiqASb96bKgW34XOZVjLUYVIq/yFAVs1a5Ydxy # your encrypted token from GitHub
artifact: aldebianpackage
draft: false
force_update: true
prerelease: true
on:
branch: develop
- provider: GitHub
description: "This is an automated prerelease deployment"
auth_token:
secure: HsE6rIUR/bsL7wBhrBgfFf3HFDkiqASb96bKgW34XOZVjLUYVIq/yFAVs1a5Ydxy # your encrypted token from GitHub
artifact: alrpmpackage
draft: false
force_update: true
prerelease: true
on:
branch: develop
after_build:
- ps: "& $env:APPVEYOR_BUILD_FOLDER/.build/04-publish.ps1"
``` | /content/code_sandbox/appveyor.yml | yaml | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,727 |
```yaml
# Read the Docs configuration file for MkDocs projects
# See path_to_url for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.11"
mkdocs:
configuration: mkdocs.yml
``` | /content/code_sandbox/.readthedocs.yaml | yaml | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 73 |
```yaml
copyright: AutomatedLab is licensed under the <a href='path_to_url license
repo_url: path_to_url
nav:
- Home: index.md
- Installation: Wiki/Basic/install.md
- Getting started:
- First steps: Wiki/Basic/gettingstarted.md
- Advanced configuration: Wiki/Advanced/automatedlabconfig.md
- Defining your lab:
- Creating a new lab: Wiki/Basic/createnewlab.md
- Networks and IP Addresses: Wiki/Basic/networksandaddresses.md
- Adding machines: Wiki/Basic/addmachines.md
- Modifying labs: Wiki/Basic/modifylab.md
- Preparing a fully offline environment: Wiki/Basic/fullyoffline.md
- Joining lab VMs to existing domain: Wiki/Basic/joindomain.md
- Parallel deployments: Wiki/Advanced/resourcenaming.md
- Roles:
- About roles: Wiki/Roles/roles.md
- ActiveDirectory: Wiki/Roles/activedirectory.md
- Office 2013, 2016: Wiki/Roles/office.md
- Sharepoint: Wiki/Roles/sharepoint.md
- Failover clustering: Wiki/Roles/failoverclustering.md
- TFS and Azure DevOps: Wiki/Roles/cicd.md
- Hyper-V: Wiki/Roles/hyperv.md
- SQL Server: Wiki/Roles/sql.md
- DSC Pull Server: Wiki/Roles/dscpull.md
- Lab Builder REST API: Wiki/Roles/restapi.md
- Dynamics 365: Wiki/Roles/dynamics365.md
- SCVMM: Wiki/Roles/scvmm.md
- SCCM/MEMCM: Wiki/Roles/configurationmanager.md
- Custom roles: Wiki/Advanced/customroles.md
- Customizing your lab:
- Installing Windows features: Wiki/Basic/installwindowsfeatures.md
- Installing software: Wiki/Basic/installsoftware.md
- Run remote commands: Wiki/Basic/invokelabcommand.md
- Use PowerShell DSC: Wiki/Advanced/usedsc.md
- Exchanging data: Wiki/Basic/exchangedata.md
- Notification system: Wiki/Advanced/notifications.md
- Connecting two labs: Wiki/Advanced/connectlabs.md
- Running on a Cluster: Wiki/Advanced/runoncluster.md
- Azure labs:
- Adding a subscription: Wiki/Basic/addazuresubscription.md
- Synchronise local lab sources: Wiki/Basic/synclabsources.md
- Mounting ISO files: Wiki/Basic/mountazureisos.md
- Using the Bastion host: Wiki/Basic/useazurebastion.md
- Sample scripts:
- Azure:
- AzureStackHub.ps1: Wiki/SampleScripts/Azure/en-us/AzureStackHub.md
- MultiForestLab 2012R2.ps1: Wiki/SampleScripts/Azure/en-us/MultiForestLab 2012R2.md
- MultiNetMultiForest.ps1: Wiki/SampleScripts/Azure/en-us/MultiNetMultiForest.md
- VpnConnectedLab.ps1: Wiki/SampleScripts/Azure/en-us/VpnConnectedLab.md
- HyperV:
- AL Loves Linux.ps1: Wiki/SampleScripts/HyperV/en-us/AL Loves Linux.md
- BigLab 2012R2 EX SQL ORCH VS OFF.ps1: Wiki/SampleScripts/HyperV/en-us/BigLab 2012R2 EX SQL ORCH VS OFF.md
- MediumLab 2012R2 SQL EX.ps1: Wiki/SampleScripts/HyperV/en-us/MediumLab 2012R2 SQL EX.md
- MediumLab 2012R2 SQL.ps1: Wiki/SampleScripts/HyperV/en-us/MediumLab 2012R2 SQL.md
- MultiForestLab 2008R2.ps1: Wiki/SampleScripts/HyperV/en-us/MultiForestLab 2008R2.md
- MultiForestLab 2012R2.ps1: Wiki/SampleScripts/HyperV/en-us/MultiForestLab 2012R2.md
- PKI Custom.ps1: Wiki/SampleScripts/HyperV/en-us/PKI Custom.md
- PKI Simple.ps1: Wiki/SampleScripts/HyperV/en-us/PKI Simple.md
- PKI Two Tier - Workgroup and Domain - Custom Production Deployment.ps1: Wiki/SampleScripts/HyperV/en-us/PKI Two Tier - Workgroup and Domain - Custom Production Deployment.md
- PKI Two Tier - Workgroup and Domain - Typical Production Deployment.ps1: Wiki/SampleScripts/HyperV/en-us/PKI Two Tier - Workgroup and Domain - Typical Production Deployment.md
- Single 10 Client with Office, VS and Reflector.ps1: Wiki/SampleScripts/HyperV/en-us/Single 10 Client with Office, VS and Reflector.md
- Single 10 Client with Office2019.ps1: Wiki/SampleScripts/HyperV/en-us/Single 10 Client with Office2019.md
- Single 10 Client.ps1: Wiki/SampleScripts/HyperV/en-us/Single 10 Client.md
- Single 2008R2 Server.ps1: Wiki/SampleScripts/HyperV/en-us/Single 2008R2 Server.md
- Single 2012R2 Server DC SQL2014 Web CA.ps1: Wiki/SampleScripts/HyperV/en-us/Single 2012R2 Server DC SQL2014 Web CA.md
- Single 2012R2 Server.ps1: Wiki/SampleScripts/HyperV/en-us/Single 2012R2 Server.md
- Single 81 Client with Office.ps1: Wiki/SampleScripts/HyperV/en-us/Single 81 Client with Office.md
- Single 81 Client.ps1: Wiki/SampleScripts/HyperV/en-us/Single 81 Client.md
- SmallLab 2012R2 EX.ps1: Wiki/SampleScripts/HyperV/en-us/SmallLab 2012R2 EX.md
- SmallLab 2012R2 Single Client.ps1: Wiki/SampleScripts/HyperV/en-us/SmallLab 2012R2 Single Client.md
- SmallLab 2012R2 Single Server.ps1: Wiki/SampleScripts/HyperV/en-us/SmallLab 2012R2 Single Server.md
- SmallLab 2012R2 SQL.ps1: Wiki/SampleScripts/HyperV/en-us/SmallLab 2012R2 SQL.md
- Introduction:
- 01 Single Win10 Client.ps1: Wiki/SampleScripts/Introduction/en-us/01 Single Win10 Client.md
- 02 Single Win10 Client (internet facing).ps1: Wiki/SampleScripts/Introduction/en-us/02 Single Win10 Client (internet facing).md
- 03 PowerShell 5 on Windows 7.ps1: Wiki/SampleScripts/Introduction/en-us/03 PowerShell 5 on Windows 7.md
- 04 Single domain-joined server.ps1: Wiki/SampleScripts/Introduction/en-us/04 Single domain-joined server.md
- 05 Single domain-joined server (internet facing).ps1: Wiki/SampleScripts/Introduction/en-us/05 Single domain-joined server (internet facing).md
- 06 SQL Server and client, domain joined.ps1: Wiki/SampleScripts/Introduction/en-us/06 SQL Server and client, domain joined.md
- 07.1 Exchange 2013 Server and client, domain joined.ps1: Wiki/SampleScripts/Introduction/en-us/07.1 Exchange 2013 Server and client, domain joined.md
- 07.2 Exchange 2016 Server and client, domain joined.ps1: Wiki/SampleScripts/Introduction/en-us/07.2 Exchange 2016 Server and client, domain joined.md
- 07.3 Exchange 2019 Server and client, domain joined.ps1: Wiki/SampleScripts/Introduction/en-us/07.3 Exchange 2019 Server and client, domain joined.md
- 08 Standalone Root CA, Sub Ca domain joined.ps1: Wiki/SampleScripts/Introduction/en-us/08 Standalone Root CA, Sub Ca domain joined.md
- 09 Web Servers with SSL certs, Root CA, domain joined.ps1: Wiki/SampleScripts/Introduction/en-us/09 Web Servers with SSL certs, Root CA, domain joined.md
- 10 Development Client, domain joined (internet facing).ps1: Wiki/SampleScripts/Introduction/en-us/10 Development Client, domain joined (internet facing).md
- 11 ISO Offline Patching.ps1: Wiki/SampleScripts/Introduction/en-us/11 ISO Offline Patching.md
- 12.1 Azure Single domain-joined server.ps1: Wiki/SampleScripts/Introduction/en-us/12.1 Azure Single domain-joined server.md
- 12.2 Azure SQL Server and client, domain joined.ps1: Wiki/SampleScripts/Introduction/en-us/12.2 Azure SQL Server and client, domain joined.md
- Scenarios:
- AGPM Lab 1.ps1: Wiki/SampleScripts/Scenarios/en-us/AGPM Lab 1.md
- AzureArcConnectedHyperV.ps1: Wiki/SampleScripts/Scenarios/en-us/AzureArcConnectedHyperV.md
- AzureDevOpsBuildAgent.ps1: Wiki/SampleScripts/Scenarios/en-us/AzureDevOpsBuildAgent.md
- AzureDevOpsCloudConnection.ps1: Wiki/SampleScripts/Scenarios/en-us/AzureDevOpsCloudConnection.md
- CM-1902.ps1: Wiki/SampleScripts/Scenarios/en-us/CM-1902.md
- CM-2002.ps1: Wiki/SampleScripts/Scenarios/en-us/CM-2002.md
- CM-2103.ps1: Wiki/SampleScripts/Scenarios/en-us/CM-2103.md
- CM-2203.ps1: Wiki/SampleScripts/Scenarios/en-us/CM-2203.md
- DSC Pull Scenario 1 (Pull Configuration).ps1: Wiki/SampleScripts/Scenarios/en-us/DSC Pull Scenario 1 (Pull Configuration).md
- DSC Pull Scenario 1 (Pull Configuration, SQL Reporting).ps1: Wiki/SampleScripts/Scenarios/en-us/DSC Pull Scenario 1 (Pull Configuration, SQL Reporting).md
- DSC Pull Scenario 2 (Pull Partial Configuration).ps1: Wiki/SampleScripts/Scenarios/en-us/DSC Pull Scenario 2 (Pull Partial Configuration).md
- DSC With Release Pipeline.ps1: Wiki/SampleScripts/Scenarios/en-us/DSC With Release Pipeline.md
- Dynamics365.ps1: Wiki/SampleScripts/Scenarios/en-us/Dynamics365.md
- ExistingDomainLab.ps1: Wiki/SampleScripts/Scenarios/en-us/ExistingDomainLab.md
- Failover Clustering 1.ps1: Wiki/SampleScripts/Scenarios/en-us/Failover Clustering 1.md
- Failover Clustering 2 (Shared Storage).ps1: Wiki/SampleScripts/Scenarios/en-us/Failover Clustering 2 (Shared Storage).md
- Failover Clustering 3 MultipleNetworks.ps1: Wiki/SampleScripts/Scenarios/en-us/Failover Clustering 3 MultipleNetworks.md
- Failover Clustering 3 MultipleNetworksAzure.ps1: Wiki/SampleScripts/Scenarios/en-us/Failover Clustering 3 MultipleNetworksAzure.md
- Hybrid Environment HyperV and Azure 1.ps1: Wiki/SampleScripts/Scenarios/en-us/Hybrid Environment HyperV and Azure 1.md
- HybridHyperVAzureArc.ps1: Wiki/SampleScripts/Scenarios/en-us/HybridHyperVAzureArc.md
- HyperVClusterWithVmm.ps1: Wiki/SampleScripts/Scenarios/en-us/HyperVClusterWithVmm.md
- InternalRouting.ps1: Wiki/SampleScripts/Scenarios/en-us/InternalRouting.md
- Lab in a Box 1 - HyperV.ps1: Wiki/SampleScripts/Scenarios/en-us/Lab in a Box 1 - HyperV.md
- Lab in a Box 2 - Azure.ps1: Wiki/SampleScripts/Scenarios/en-us/Lab in a Box 2 - Azure.md
- Lab in a Box 3 - Build worker.ps1: Wiki/SampleScripts/Scenarios/en-us/Lab in a Box 3 - Build worker.md
- MDT Lab 1, MDT Server 1.ps1: Wiki/SampleScripts/Scenarios/en-us/MDT Lab 1, MDT Server 1.md
- MDT Lab 2, DC and MDT Server.ps1: Wiki/SampleScripts/Scenarios/en-us/MDT Lab 2, DC and MDT Server.md
- Multi-AD Forest with Trusts.ps1: Wiki/SampleScripts/Scenarios/en-us/Multi-AD Forest with Trusts.md
- NuGetServer.ps1: Wiki/SampleScripts/Scenarios/en-us/NuGetServer.md
- ProGet Lab - Azure.ps1: Wiki/SampleScripts/Scenarios/en-us/ProGet Lab - Azure.md
- ProGet Lab - HyperV.ps1: Wiki/SampleScripts/Scenarios/en-us/ProGet Lab - HyperV.md
- RemoteDesktopServices.ps1: Wiki/SampleScripts/Scenarios/en-us/RemoteDesktopServices.md
- SCCM Lab 1.ps1: Wiki/SampleScripts/Scenarios/en-us/SCCM Lab 1.md
- SCOMDistributed.ps1: Wiki/SampleScripts/Scenarios/en-us/SCOMDistributed.md
- SCVMM2019.ps1: Wiki/SampleScripts/Scenarios/en-us/SCVMM2019.md
- SCVMM2022.ps1: Wiki/SampleScripts/Scenarios/en-us/SCVMM2022.md
- SharePoint2016.ps1: Wiki/SampleScripts/Scenarios/en-us/SharePoint2016.md
- TFS 2015 Deployment.ps1: Wiki/SampleScripts/Scenarios/en-us/TFS 2015 Deployment.md
- TFS 2017 Deployment.ps1: Wiki/SampleScripts/Scenarios/en-us/TFS 2017 Deployment.md
- WindowsAdminCenter-OnPrem.ps1: Wiki/SampleScripts/Scenarios/en-us/WindowsAdminCenter-OnPrem.md
- WindowsAdminCenter.ps1: Wiki/SampleScripts/Scenarios/en-us/WindowsAdminCenter.md
- WinRM clients with SSL.ps1: Wiki/SampleScripts/Scenarios/en-us/WinRM clients with SSL.md
- VMWare:
- VMWare Single Server.ps1: Wiki/SampleScripts/VMWare/en-us/VMWare Single Server.md
- Workshops:
- ADPowerShellWorkshopLab.ps1: Wiki/SampleScripts/Workshops/en-us/ADPowerShellWorkshopLab.md
- ADRecoveryLab - Azure.ps1: Wiki/SampleScripts/Workshops/en-us/ADRecoveryLab - Azure.md
- ADRecoveryLab - HyperV.ps1: Wiki/SampleScripts/Workshops/en-us/ADRecoveryLab - HyperV.md
- DFSHC - Azure.ps1: Wiki/SampleScripts/Workshops/en-us/DFSHC - Azure.md
- DFSHC - HyperV.ps1: Wiki/SampleScripts/Workshops/en-us/DFSHC - HyperV.md
- Kerberos 101 Lab - HyperV.ps1: Wiki/SampleScripts/Workshops/en-us/Kerberos 101 Lab - HyperV.md
- Kerberos 101 Lab with Linux - HyperV.ps1: Wiki/SampleScripts/Workshops/en-us/Kerberos 101 Lab with Linux - HyperV.md
- PowerShell Lab - Azure.ps1: Wiki/SampleScripts/Workshops/en-us/PowerShell Lab - Azure.md
- PowerShell Lab - HyperV with Internet.ps1: Wiki/SampleScripts/Workshops/en-us/PowerShell Lab - HyperV with Internet.md
- PowerShell Lab - HyperV.ps1: Wiki/SampleScripts/Workshops/en-us/PowerShell Lab - HyperV.md
- Lab telemetry: Wiki/About/telemetry.md
- Version history: path_to_url
- Module help:
- Add-HostEntry: HostsFile/en-us/Add-HostEntry.md
- Add-LabAzureAppServicePlanDefinition: AutomatedLabDefinition/en-us/Add-LabAzureAppServicePlanDefinition.md
- Add-LabAzureSubscription: AutomatedLabCore/en-us/Add-LabAzureSubscription.md
- Add-LabAzureWebAppDefinition: AutomatedLabDefinition/en-us/Add-LabAzureWebAppDefinition.md
- Add-LabCertificate: AutomatedLabCore/en-us/Add-LabCertificate.md
- Add-LabDiskDefinition: AutomatedLabDefinition/en-us/Add-LabDiskDefinition.md
- Add-LabDomainDefinition: AutomatedLabDefinition/en-us/Add-LabDomainDefinition.md
- Add-LabIsoImageDefinition: AutomatedLabDefinition/en-us/Add-LabIsoImageDefinition.md
- Add-LabMachineDefinition: AutomatedLabDefinition/en-us/Add-LabMachineDefinition.md
- Add-LabVirtualNetworkDefinition: AutomatedLabDefinition/en-us/Add-LabVirtualNetworkDefinition.md
- Add-LabVMUserRight: AutomatedLabCore/en-us/Add-LabVMUserRight.md
- Add-LabVMWareSettings: AutomatedLabCore/en-us/Add-LabVMWareSettings.md
- Add-LabWacManagedNode: AutomatedLabCore/en-us/Add-LabWacManagedNode.md
- Add-LWAzureLoadBalancedPort: AutomatedLabWorker/en-us/Add-LWAzureLoadBalancedPort.md
- Add-LWVMVHDX: AutomatedLabWorker/en-us/Add-LWVMVHDX.md
- Add-UnattendedNetworkAdapter: AutomatedLabUnattended/en-us/Add-UnattendedNetworkAdapter.md
- Add-UnattendedRenameNetworkAdapters: AutomatedLabUnattended/en-us/Add-UnattendedRenameNetworkAdapters.md
- Add-UnattendedSynchronousCommand: AutomatedLabUnattended/en-us/Add-UnattendedSynchronousCommand.md
- Checkpoint-LabVM: AutomatedLabCore/en-us/Checkpoint-LabVM.md
- Checkpoint-LWAzureVM: AutomatedLabWorker/en-us/Checkpoint-LWAzureVM.md
- Checkpoint-LWHypervVM: AutomatedLabWorker/en-us/Checkpoint-LWHypervVM.md
- Clear-HostFile: HostsFile/en-us/Clear-HostFile.md
- Clear-Lab: AutomatedLabCore/en-us/Clear-Lab.md
- Clear-LabCache: AutomatedLabCore/en-us/Clear-LabCache.md
- Connect-Lab: AutomatedLabCore/en-us/Connect-Lab.md
- Connect-LabVM: AutomatedLabCore/en-us/Connect-LabVM.md
- Connect-LWAzureLabSourcesDrive: AutomatedLabWorker/en-us/Connect-LWAzureLabSourcesDrive.md
- Copy-LabALCommon: AutomatedLabCore/en-us/Copy-LabALCommon.md
- Copy-LabFileItem: AutomatedLabCore/en-us/Copy-LabFileItem.md
- Disable-LabAutoLogon: AutomatedLabCore/en-us/Disable-LabAutoLogon.md
- Disable-LabMachineAutoShutdown: AutomatedLabCore/en-us/Disable-LabMachineAutoShutdown.md
- Disable-LabTelemetry: AutomatedLabCore/en-us/Disable-LabTelemetry.md
- Disable-LabVMFirewallGroup: AutomatedLabCore/en-us/Disable-LabVMFirewallGroup.md
- Disable-LWAzureAutoShutdown: AutomatedLabWorker/en-us/Disable-LWAzureAutoShutdown.md
- Disconnect-Lab: AutomatedLabCore/en-us/Disconnect-Lab.md
- Dismount-LabIsoImage: AutomatedLabCore/en-us/Dismount-LabIsoImage.md
- Dismount-LWAzureIsoImage: AutomatedLabWorker/en-us/Dismount-LWAzureIsoImage.md
- Dismount-LWIsoImage: AutomatedLabWorker/en-us/Dismount-LWIsoImage.md
- Enable-LabAutoLogon: AutomatedLabCore/en-us/Enable-LabAutoLogon.md
- Enable-LabAzureJitAccess: AutomatedLabCore/en-us/Enable-LabAzureJitAccess.md
- Enable-LabCertificateAutoenrollment: AutomatedLabCore/en-us/Enable-LabCertificateAutoenrollment.md
- Enable-LabHostRemoting: AutomatedLabCore/en-us/Enable-LabHostRemoting.md
- Enable-LabInternalRouting: AutomatedLabCore/en-us/Enable-LabInternalRouting.md
- Enable-LabMachineAutoShutdown: AutomatedLabCore/en-us/Enable-LabMachineAutoShutdown.md
- Enable-LabTelemetry: AutomatedLabCore/en-us/Enable-LabTelemetry.md
- Enable-LabVMFirewallGroup: AutomatedLabCore/en-us/Enable-LabVMFirewallGroup.md
- Enable-LabVMRemoting: AutomatedLabCore/en-us/Enable-LabVMRemoting.md
- Enable-LWAzureAutoShutdown: AutomatedLabWorker/en-us/Enable-LWAzureAutoShutdown.md
- Enable-LWAzureVMRemoting: AutomatedLabWorker/en-us/Enable-LWAzureVMRemoting.md
- Enable-LWAzureWinRm: AutomatedLabWorker/en-us/Enable-LWAzureWinRm.md
- Enable-LWHypervVMRemoting: AutomatedLabWorker/en-us/Enable-LWHypervVMRemoting.md
- Enable-LWVMWareVMRemoting: AutomatedLabWorker/en-us/Enable-LWVMWareVMRemoting.md
- Enter-LabPSSession: AutomatedLabCore/en-us/Enter-LabPSSession.md
- Export-Lab: AutomatedLabCore/en-us/Export-Lab.md
- Export-LabDefinition: AutomatedLabDefinition/en-us/Export-LabDefinition.md
- Export-LabSnippet: AutomatedLab.Recipe/en-us/Export-LabSnippet.md
- Export-UnattendedFile: AutomatedLabUnattended/en-us/Export-UnattendedFile.md
- Get-CallerPreference: PSLog/en-us/Get-CallerPreference.md
- Get-DiskSpeed: AutomatedLabDefinition/en-us/Get-DiskSpeed.md
- Get-HostEntry: HostsFile/en-us/Get-HostEntry.md
- Get-HostFile: HostsFile/en-us/Get-HostFile.md
- Get-Lab: AutomatedLabCore/en-us/Get-Lab.md
- Get-LabAvailableAddresseSpace: AutomatedLabDefinition/en-us/Get-LabAvailableAddresseSpace.md
- Get-LabAvailableOperatingSystem: AutomatedLabCore/en-us/Get-LabAvailableOperatingSystem.md
- Get-LabAzureAppServicePlan: AutomatedLabCore/en-us/Get-LabAzureAppServicePlan.md
- Get-LabAzureAppServicePlanDefinition: AutomatedLabDefinition/en-us/Get-LabAzureAppServicePlanDefinition.md
- Get-LabAzureAvailableRoleSize: AutomatedLabCore/en-us/Get-LabAzureAvailableRoleSize.md
- Get-LabAzureAvailableSku: AutomatedLabCore/en-us/Get-LabAzureAvailableSku.md
- Get-LabAzureCertificate: AutomatedLabCore/en-us/Get-LabAzureCertificate.md
- Get-LabAzureDefaultLocation: AutomatedLabCore/en-us/Get-LabAzureDefaultLocation.md
- Get-LabAzureDefaultResourceGroup: AutomatedLabCore/en-us/Get-LabAzureDefaultResourceGroup.md
- Get-LabAzureLabSourcesContent: AutomatedLabCore/en-us/Get-LabAzureLabSourcesContent.md
- Get-LabAzureLabSourcesStorage: AutomatedLabCore/en-us/Get-LabAzureLabSourcesStorage.md
- Get-LabAzureLoadBalancedPort: AutomatedLabWorker/en-us/Get-LabAzureLoadBalancedPort.md
- Get-LabAzureLocation: AutomatedLabCore/en-us/Get-LabAzureLocation.md
- Get-LabAzureResourceGroup: AutomatedLabCore/en-us/Get-LabAzureResourceGroup.md
- Get-LabAzureSubscription: AutomatedLabCore/en-us/Get-LabAzureSubscription.md
- Get-LabAzureWebApp: AutomatedLabCore/en-us/Get-LabAzureWebApp.md
- Get-LabAzureWebAppDefinition: AutomatedLabDefinition/en-us/Get-LabAzureWebAppDefinition.md
- Get-LabAzureWebAppStatus: AutomatedLabCore/en-us/Get-LabAzureWebAppStatus.md
- Get-LabBuildStep: AutomatedLabCore/en-us/Get-LabBuildStep.md
- Get-LabCache: AutomatedLabCore/en-us/Get-LabCache.md
- Get-LabCertificate: AutomatedLabCore/en-us/Get-LabCertificate.md
- Get-LabCimSession: AutomatedLabCore/en-us/Get-LabCimSession.md
- Get-LabConfigurationItem: AutomatedLabCore/en-us/Get-LabConfigurationItem.md
- Get-LabDefinition: AutomatedLabDefinition/en-us/Get-LabDefinition.md
- Get-LabDomainDefinition: AutomatedLabDefinition/en-us/Get-LabDomainDefinition.md
- Get-LabHyperVAvailableMemory: AutomatedLabCore/en-us/Get-LabHyperVAvailableMemory.md
- Get-LabInstallationActivity: AutomatedLabDefinition/en-us/Get-LabInstallationActivity.md
- Get-LabInternetFile: AutomatedLabCore/en-us/Get-LabInternetFile.md
- Get-LabIsoImageDefinition: AutomatedLabDefinition/en-us/Get-LabIsoImageDefinition.md
- Get-LabIssuingCA: AutomatedLabCore/en-us/Get-LabIssuingCA.md
- Get-LabMachineAutoShutdown: AutomatedLabCore/en-us/Get-LabMachineAutoShutdown.md
- Get-LabMachineDefinition: AutomatedLabDefinition/en-us/Get-LabMachineDefinition.md
- Get-LabMachineRoleDefinition: AutomatedLabDefinition/en-us/Get-LabMachineRoleDefinition.md
- Get-LabPostInstallationActivity: AutomatedLabDefinition/en-us/Get-LabPostInstallationActivity.md
- Get-LabPreInstallationActivity: AutomatedLabDefinition/en-us/Get-LabPreInstallationActivity.md
- Get-LabPSSession: AutomatedLabCore/en-us/Get-LabPSSession.md
- Get-LabRecipe: AutomatedLab.Recipe/en-us/Get-LabRecipe.md
- Get-LabReleaseStep: AutomatedLabCore/en-us/Get-LabReleaseStep.md
- Get-LabSnippet: AutomatedLab.Recipe/en-us/Get-LabSnippet.md
- Get-LabSoftwarePackage: AutomatedLabCore/en-us/Get-LabSoftwarePackage.md
- Get-LabSourcesLocation: AutomatedLabCore/en-us/Get-LabSourcesLocation.md
- Get-LabSourcesLocationInternal: AutomatedLabCore/en-us/Get-LabSourcesLocationInternal.md
- Get-LabSshKnownHost: AutomatedLabCore/en-us/Get-LabSshKnownHost.md
- Get-LabTfsFeed: AutomatedLabCore/en-us/Get-LabTfsFeed.md
- Get-LabTfsParameter: AutomatedLabCore/en-us/Get-LabTfsParameter.md
- Get-LabTfsUri: AutomatedLabCore/en-us/Get-LabTfsUri.md
- Get-LabVariable: AutomatedLabCore/en-us/Get-LabVariable.md
- Get-LabVHDX: AutomatedLabCore/en-us/Get-LabVHDX.md
- Get-LabVirtualNetwork: AutomatedLabDefinition/en-us/Get-LabVirtualNetwork.md
- Get-LabVirtualNetworkDefinition: AutomatedLabDefinition/en-us/Get-LabVirtualNetworkDefinition.md
- Get-LabVM: AutomatedLabCore/en-us/Get-LabVM.md
- Get-LabVMDotNetFrameworkVersion: AutomatedLabCore/en-us/Get-LabVMDotNetFrameworkVersion.md
- Get-LabVMRdpFile: AutomatedLabCore/en-us/Get-LabVMRdpFile.md
- Get-LabVMSnapshot: AutomatedLabCore/en-us/Get-LabVMSnapshot.md
- Get-LabVMStatus: AutomatedLabCore/en-us/Get-LabVMStatus.md
- Get-LabVMUacStatus: AutomatedLabCore/en-us/Get-LabVMUacStatus.md
- Get-LabVMUptime: AutomatedLabCore/en-us/Get-LabVMUptime.md
- Get-LabVolumesOnPhysicalDisks: AutomatedLabDefinition/en-us/Get-LabVolumesOnPhysicalDisks.md
- Get-LabWindowsFeature: AutomatedLabCore/en-us/Get-LabWindowsFeature.md
- Get-LWAzureAutoShutdown: AutomatedLabWorker/en-us/Get-LWAzureAutoShutdown.md
- Get-LWAzureLoadBalancedPort: AutomatedLabWorker/en-us/Get-LWAzureLoadBalancedPort.md
- Get-LWAzureNetworkSwitch: AutomatedLabWorker/en-us/Get-LWAzureNetworkSwitch.md
- Get-LWAzureSku: AutomatedLabWorker/en-us/Get-LWAzureSku.md
- Get-LWAzureVm: AutomatedLabWorker/en-us/Get-LWAzureVm.md
- Get-LWAzureVMConnectionInfo: AutomatedLabWorker/en-us/Get-LWAzureVMConnectionInfo.md
- Get-LWAzureVmSize: AutomatedLabWorker/en-us/Get-LWAzureVmSize.md
- Get-LWAzureVmSnapshot: AutomatedLabWorker/en-us/Get-LWAzureVmSnapshot.md
- Get-LWAzureVMStatus: AutomatedLabWorker/en-us/Get-LWAzureVMStatus.md
- Get-LWAzureWindowsFeature: AutomatedLabWorker/en-us/Get-LWAzureWindowsFeature.md
- Get-LWHypervVM: AutomatedLabWorker/en-us/Get-LWHypervVM.md
- Get-LWHypervVMDescription: AutomatedLabWorker/en-us/Get-LWHypervVMDescription.md
- Get-LWHypervVMSnapshot: AutomatedLabWorker/en-us/Get-LWHypervVMSnapshot.md
- Get-LWHypervVMStatus: AutomatedLabWorker/en-us/Get-LWHypervVMStatus.md
- Get-LWHypervWindowsFeature: AutomatedLabWorker/en-us/Get-LWHypervWindowsFeature.md
- Get-LWVMWareNetworkSwitch: AutomatedLabWorker/en-us/Get-LWVMWareNetworkSwitch.md
- Get-LWVMWareVMStatus: AutomatedLabWorker/en-us/Get-LWVMWareVMStatus.md
- Get-UnattendedContent: AutomatedLabUnattended/en-us/Get-UnattendedContent.md
- Import-Lab: AutomatedLabCore/en-us/Import-Lab.md
- Import-LabAzureCertificate: AutomatedLabCore/en-us/Import-LabAzureCertificate.md
- Import-LabDefinition: AutomatedLabDefinition/en-us/Import-LabDefinition.md
- Import-LabTestResult: AutomatedLabTest/en-us/Import-LabTestResult.md
- Import-UnattendedContent: AutomatedLabUnattended/en-us/Import-UnattendedContent.md
- Import-UnattendedFile: AutomatedLabUnattended/en-us/Import-UnattendedFile.md
- Initialize-LabWindowsActivation: AutomatedLabCore/en-us/Initialize-LabWindowsActivation.md
- Initialize-LWAzureVM: AutomatedLabWorker/en-us/Initialize-LWAzureVM.md
- Install-Lab: AutomatedLabCore/en-us/Install-Lab.md
- Install-LabADDSTrust: AutomatedLabCore/en-us/Install-LabADDSTrust.md
- Install-LabAdfs: AutomatedLabCore/en-us/Install-LabAdfs.md
- Install-LabAdfsProxy: AutomatedLabCore/en-us/Install-LabAdfsProxy.md
- Install-LabAzureRequiredModule: AutomatedLabCore/en-us/Install-LabAzureRequiredModule.md
- Install-LabAzureServices: AutomatedLabCore/en-us/Install-LabAzureServices.md
- Install-LabBuildWorker: AutomatedLabCore/en-us/Install-LabBuildWorker.md
- Install-LabConfigurationManager: AutomatedLabCore/en-us/Install-LabConfigurationManager.md
- Install-LabDcs: AutomatedLabCore/en-us/Install-LabDcs.md
- Install-LabDnsForwarder: AutomatedLabCore/en-us/Install-LabDnsForwarder.md
- Install-LabDscClient: AutomatedLabCore/en-us/Install-LabDscClient.md
- Install-LabDscPullServer: AutomatedLabCore/en-us/Install-LabDscPullServer.md
- Install-LabDynamics: AutomatedLabCore/en-us/Install-LabDynamics.md
- Install-LabFailoverCluster: AutomatedLabCore/en-us/Install-LabFailoverCluster.md
- Install-LabFirstChildDcs: AutomatedLabCore/en-us/Install-LabFirstChildDcs.md
- Install-LabHyperV: AutomatedLabCore/en-us/Install-LabHyperV.md
- Install-LabOffice2013: AutomatedLabCore/en-us/Install-LabOffice2013.md
- Install-LabOffice2016: AutomatedLabCore/en-us/Install-LabOffice2016.md
- Install-LabRdsCertificate: AutomatedLabCore/en-us/Install-LabRdsCertificate.md
- Install-LabRemoteDesktopServices: AutomatedLabCore/en-us/Install-LabRemoteDesktopServices.md
- Install-LabRootDcs: AutomatedLabCore/en-us/Install-LabRootDcs.md
- Install-LabRouting: AutomatedLabCore/en-us/Install-LabRouting.md
- Install-LabScom: AutomatedLabCore/en-us/Install-LabScom.md
- Install-LabScvmm: AutomatedLabCore/en-us/Install-LabScvmm.md
- Install-LabSoftwarePackage: AutomatedLabCore/en-us/Install-LabSoftwarePackage.md
- Install-LabSoftwarePackages: AutomatedLabCore/en-us/Install-LabSoftwarePackages.md
- Install-LabSqlSampleDatabases: AutomatedLabCore/en-us/Install-LabSqlSampleDatabases.md
- Install-LabSqlServers: AutomatedLabCore/en-us/Install-LabSqlServers.md
- Install-LabSshKnownHost: AutomatedLabCore/en-us/Install-LabSshKnownHost.md
- Install-LabTeamFoundationEnvironment: AutomatedLabCore/en-us/Install-LabTeamFoundationEnvironment.md
- Install-LabWindowsAdminCenter: AutomatedLabCore/en-us/Install-LabWindowsAdminCenter.md
- Install-LabWindowsFeature: AutomatedLabCore/en-us/Install-LabWindowsFeature.md
- Install-LWAzureWindowsFeature: AutomatedLabWorker/en-us/Install-LWAzureWindowsFeature.md
- Install-LWHypervWindowsFeature: AutomatedLabWorker/en-us/Install-LWHypervWindowsFeature.md
- Install-LWLabCAServers: AutomatedLabWorker/en-us/Install-LWLabCAServers.md
- Install-LWLabCAServers2008: AutomatedLabWorker/en-us/Install-LWLabCAServers2008.md
- Invoke-LabCommand: AutomatedLabCore/en-us/Invoke-LabCommand.md
- Invoke-LabDscConfiguration: AutomatedLabCore/en-us/Invoke-LabDscConfiguration.md
- Invoke-LabPester: AutomatedLabTest/en-us/Invoke-LabPester.md
- Invoke-LabRecipe: AutomatedLab.Recipe/en-us/Invoke-LabRecipe.md
- Invoke-LabSnippet: AutomatedLab.Recipe/en-us/Invoke-LabSnippet.md
- Invoke-LWCommand: AutomatedLabWorker/en-us/Invoke-LWCommand.md
- Join-LabVMDomain: AutomatedLabCore/en-us/Join-LabVMDomain.md
- Mount-LabIsoImage: AutomatedLabCore/en-us/Mount-LabIsoImage.md
- Mount-LWAzureIsoImage: AutomatedLabWorker/en-us/Mount-LWAzureIsoImage.md
- Mount-LWIsoImage: AutomatedLabWorker/en-us/Mount-LWIsoImage.md
- New-LabADSubnet: AutomatedLabCore/en-us/New-LabADSubnet.md
- New-LabAzureAppServicePlan: AutomatedLabCore/en-us/New-LabAzureAppServicePlan.md
- New-LabAzureLabSourcesStorage: AutomatedLabCore/en-us/New-LabAzureLabSourcesStorage.md
- New-LabAzureResourceGroupDeployment: AutomatedLabWorker/en-us/New-LabAzureResourceGroupDeployment.md
- New-LabAzureRmResourceGroup: AutomatedLabCore/en-us/New-LabAzureRmResourceGroup.md
- New-LabAzureWebApp: AutomatedLabCore/en-us/New-LabAzureWebApp.md
- New-LabBaseImages: AutomatedLabCore/en-us/New-LabBaseImages.md
- New-LabCATemplate: AutomatedLabCore/en-us/New-LabCATemplate.md
- New-LabCimSession: AutomatedLabCore/en-us/New-LabCimSession.md
- New-LabDefinition: AutomatedLabDefinition/en-us/New-LabDefinition.md
- New-LabNetworkAdapterDefinition: AutomatedLabDefinition/en-us/New-LabNetworkAdapterDefinition.md
- New-LabPesterTest: AutomatedLabTest/en-us/New-LabPesterTest.md
- New-LabPSSession: AutomatedLabCore/en-us/New-LabPSSession.md
- New-LabRecipe: AutomatedLab.Recipe/en-us/New-LabRecipe.md
- New-LabReleasePipeline: AutomatedLabCore/en-us/New-LabReleasePipeline.md
- New-LabSnippet: AutomatedLab.Recipe/en-us/New-LabSnippet.md
- New-LabSourcesFolder: AutomatedLabCore/en-us/New-LabSourcesFolder.md
- New-LabTfsFeed: AutomatedLabCore/en-us/New-LabTfsFeed.md
- New-LabVHDX: AutomatedLabCore/en-us/New-LabVHDX.md
- New-LabVM: AutomatedLabCore/en-us/New-LabVM.md
- New-LWAzureLoadBalancer: AutomatedLabWorker/en-us/New-LWAzureLoadBalancer.md
- New-LWHypervNetworkSwitch: AutomatedLabWorker/en-us/New-LWHypervNetworkSwitch.md
- New-LWHypervVM: AutomatedLabWorker/en-us/New-LWHypervVM.md
- New-LWReferenceVHDX: AutomatedLabWorker/en-us/New-LWReferenceVHDX.md
- New-LWVHDX: AutomatedLabWorker/en-us/New-LWVHDX.md
- New-LWVMWareVM: AutomatedLabWorker/en-us/New-LWVMWareVM.md
- Open-LabTfsSite: AutomatedLabCore/en-us/Open-LabTfsSite.md
- Receive-Directory: PSFileTransfer/en-us/Receive-Directory.md
- Receive-File: PSFileTransfer/en-us/Receive-File.md
- Register-LabArgumentCompleters: AutomatedLabCore/en-us/Register-LabArgumentCompleters.md
- Register-LabAzureRequiredResourceProvider: AutomatedLabCore/en-us/Register-LabAzureRequiredResourceProvider.md
- Remove-HostEntry: HostsFile/en-us/Remove-HostEntry.md
- Remove-Lab: AutomatedLabCore/en-us/Remove-Lab.md
- Remove-LabAzureLabSourcesStorage: AutomatedLabCore/en-us/Remove-LabAzureLabSourcesStorage.md
- Remove-LabAzureResourceGroup: AutomatedLabCore/en-us/Remove-LabAzureResourceGroup.md
- Remove-LabCimSession: AutomatedLabCore/en-us/Remove-LabCimSession.md
- Remove-LabDeploymentFiles: AutomatedLabCore/en-us/Remove-LabDeploymentFiles.md
- Remove-LabDomainDefinition: AutomatedLabDefinition/en-us/Remove-LabDomainDefinition.md
- Remove-LabDscLocalConfigurationManagerConfiguration: AutomatedLabCore/en-us/Remove-LabDscLocalConfigurationManagerConfiguration.md
- Remove-LabIsoImageDefinition: AutomatedLabDefinition/en-us/Remove-LabIsoImageDefinition.md
- Remove-LabMachineDefinition: AutomatedLabDefinition/en-us/Remove-LabMachineDefinition.md
- Remove-LabPSSession: AutomatedLabCore/en-us/Remove-LabPSSession.md
- Remove-LabRecipe: AutomatedLab.Recipe/en-us/Remove-LabRecipe.md
- Remove-LabSnippet: AutomatedLab.Recipe/en-us/Remove-LabSnippet.md
- Remove-LabVariable: AutomatedLabCore/en-us/Remove-LabVariable.md
- Remove-LabVirtualNetworkDefinition: AutomatedLabDefinition/en-us/Remove-LabVirtualNetworkDefinition.md
- Remove-LabVM: AutomatedLabCore/en-us/Remove-LabVM.md
- Remove-LabVMSnapshot: AutomatedLabCore/en-us/Remove-LabVMSnapshot.md
- Remove-LWAzureLoadBalancer: AutomatedLabWorker/en-us/Remove-LWAzureLoadBalancer.md
- Remove-LWAzureRecoveryServicesVault: AutomatedLabWorker/en-us/Remove-LWAzureRecoveryServicesVault.md
- Remove-LWAzureVM: AutomatedLabWorker/en-us/Remove-LWAzureVM.md
- Remove-LWAzureVmSnapshot: AutomatedLabWorker/en-us/Remove-LWAzureVmSnapshot.md
- Remove-LWHypervVM: AutomatedLabWorker/en-us/Remove-LWHypervVM.md
- Remove-LWHypervVMSnapshot: AutomatedLabWorker/en-us/Remove-LWHypervVMSnapshot.md
- Remove-LWNetworkSwitch: AutomatedLabWorker/en-us/Remove-LWNetworkSwitch.md
- Remove-LWVHDX: AutomatedLabWorker/en-us/Remove-LWVHDX.md
- Remove-LWVMWareVM: AutomatedLabWorker/en-us/Remove-LWVMWareVM.md
- Repair-LabDuplicateIpAddresses: AutomatedLabDefinition/en-us/Repair-LabDuplicateIpAddresses.md
- Repair-LWHypervNetworkConfig: AutomatedLabWorker/en-us/Repair-LWHypervNetworkConfig.md
- Request-LabAzureJitAccess: AutomatedLabCore/en-us/Request-LabAzureJitAccess.md
- Request-LabCertificate: AutomatedLabCore/en-us/Request-LabCertificate.md
- Reset-AutomatedLab: AutomatedLabCore/en-us/Reset-AutomatedLab.md
- Restart-LabVM: AutomatedLabCore/en-us/Restart-LabVM.md
- Restart-ServiceResilient: AutomatedLabCore/en-us/Restart-ServiceResilient.md
- Restore-LabConnection: AutomatedLabCore/en-us/Restore-LabConnection.md
- Restore-LabVMSnapshot: AutomatedLabCore/en-us/Restore-LabVMSnapshot.md
- Restore-LWAzureVmSnapshot: AutomatedLabWorker/en-us/Restore-LWAzureVmSnapshot.md
- Restore-LWHypervVMSnapshot: AutomatedLabWorker/en-us/Restore-LWHypervVMSnapshot.md
- Save-LabRecipe: AutomatedLab.Recipe/en-us/Save-LabRecipe.md
- Save-LabVM: AutomatedLabCore/en-us/Save-LabVM.md
- Save-LWHypervVM: AutomatedLabWorker/en-us/Save-LWHypervVM.md
- Save-LWVMWareVM: AutomatedLabWorker/en-us/Save-LWVMWareVM.md
- Send-ALNotification: AutomatedLabNotifications/en-us/Send-ALNotification.md
- Send-Directory: PSFileTransfer/en-us/Send-Directory.md
- Send-File: PSFileTransfer/en-us/Send-File.md
- Set-LabAzureDefaultLocation: AutomatedLabCore/en-us/Set-LabAzureDefaultLocation.md
- Set-LabAzureWebAppContent: AutomatedLabCore/en-us/Set-LabAzureWebAppContent.md
- Set-LabDefaultOperatingSystem: AutomatedLabCore/en-us/Set-LabDefaultOperatingSystem.md
- Set-LabDefaultVirtualizationEngine: AutomatedLabCore/en-us/Set-LabDefaultVirtualizationEngine.md
- Set-LabDefinition: AutomatedLabDefinition/en-us/Set-LabDefinition.md
- Set-LabDscLocalConfigurationManagerConfiguration: AutomatedLabCore/en-us/Set-LabDscLocalConfigurationManagerConfiguration.md
- Set-LabGlobalNamePrefix: AutomatedLabCore/en-us/Set-LabGlobalNamePrefix.md
- Set-LabInstallationCredential: AutomatedLabCore/en-us/Set-LabInstallationCredential.md
- Set-LabLocalVirtualMachineDiskAuto: AutomatedLabDefinition/en-us/Set-LabLocalVirtualMachineDiskAuto.md
- Set-LabSnippet: AutomatedLab.Recipe/en-us/Set-LabSnippet.md
- Set-LabVMUacStatus: AutomatedLabCore/en-us/Set-LabVMUacStatus.md
- Set-LWAzureDnsServer: AutomatedLabWorker/en-us/Set-LWAzureDnsServer.md
- Set-LWHypervVMDescription: AutomatedLabWorker/en-us/Set-LWHypervVMDescription.md
- Set-UnattendedAdministratorName: AutomatedLabUnattended/en-us/Set-UnattendedAdministratorName.md
- Set-UnattendedAdministratorPassword: AutomatedLabUnattended/en-us/Set-UnattendedAdministratorPassword.md
- Set-UnattendedAntiMalware: AutomatedLabUnattended/en-us/Set-UnattendedAntiMalware.md
- Set-UnattendedAutoLogon: AutomatedLabUnattended/en-us/Set-UnattendedAutoLogon.md
- Set-UnattendedComputerName: AutomatedLabUnattended/en-us/Set-UnattendedComputerName.md
- Set-UnattendedDomain: AutomatedLabUnattended/en-us/Set-UnattendedDomain.md
- Set-UnattendedFirewallState: AutomatedLabUnattended/en-us/Set-UnattendedFirewallState.md
- Set-UnattendedIpSettings: AutomatedLabUnattended/en-us/Set-UnattendedIpSettings.md
- Set-UnattendedLocalIntranetSites: AutomatedLabUnattended/en-us/Set-UnattendedLocalIntranetSites.md
- Set-UnattendedPackage: AutomatedLabUnattended/en-us/Set-UnattendedPackage.md
- Set-UnattendedProductKey: AutomatedLabUnattended/en-us/Set-UnattendedProductKey.md
- Set-UnattendedTimeZone: AutomatedLabUnattended/en-us/Set-UnattendedTimeZone.md
- Set-UnattendedUserLocale: AutomatedLabUnattended/en-us/Set-UnattendedUserLocale.md
- Set-UnattendedWorkgroup: AutomatedLabUnattended/en-us/Set-UnattendedWorkgroup.md
- Show-LabDeploymentSummary: AutomatedLabCore/en-us/Show-LabDeploymentSummary.md
- Start-LabAzureWebApp: AutomatedLabCore/en-us/Start-LabAzureWebApp.md
- Start-LabVM: AutomatedLabCore/en-us/Start-LabVM.md
- Start-LWAzureVM: AutomatedLabWorker/en-us/Start-LWAzureVM.md
- Start-LWHypervVM: AutomatedLabWorker/en-us/Start-LWHypervVM.md
- Start-LWVMWareVM: AutomatedLabWorker/en-us/Start-LWVMWareVM.md
- Stop-LabAzureWebApp: AutomatedLabCore/en-us/Stop-LabAzureWebApp.md
- Stop-LabVM: AutomatedLabCore/en-us/Stop-LabVM.md
- Stop-LWAzureVM: AutomatedLabWorker/en-us/Stop-LWAzureVM.md
- Stop-LWHypervVM: AutomatedLabWorker/en-us/Stop-LWHypervVM.md
- Stop-LWVMWareVM: AutomatedLabWorker/en-us/Stop-LWVMWareVM.md
- Sync-LabActiveDirectory: AutomatedLabCore/en-us/Sync-LabActiveDirectory.md
- Sync-LabAzureLabSources: AutomatedLabCore/en-us/Sync-LabAzureLabSources.md
- Test-IpInSameSameNetwork: AutomatedLabWorker/en-us/Test-IpInSameSameNetwork.md
- Test-LabADReady: AutomatedLabCore/en-us/Test-LabADReady.md
- Test-LabAutoLogon: AutomatedLabCore/en-us/Test-LabAutoLogon.md
- Test-LabAzureLabSourcesStorage: AutomatedLabCore/en-us/Test-LabAzureLabSourcesStorage.md
- Test-LabAzureModuleAvailability: AutomatedLabCore/en-us/Test-LabAzureModuleAvailability.md
- Test-LabCATemplate: AutomatedLabCore/en-us/Test-LabCATemplate.md
- Test-LabDefinition: AutomatedLabDefinition/en-us/Test-LabDefinition.md
- Test-LabDeployment: AutomatedLabTest/en-us/Test-LabDeployment.md
- Test-LabHostConnected: AutomatedLabCore/en-us/Test-LabHostConnected.md
- Test-LabHostRemoting: AutomatedLabCore/en-us/Test-LabHostRemoting.md
- Test-LabMachineInternetConnectivity: AutomatedLabCore/en-us/Test-LabMachineInternetConnectivity.md
- Test-LabPathIsOnLabAzureLabSourcesStorage: AutomatedLabCore/en-us/Test-LabPathIsOnLabAzureLabSourcesStorage.md
- Test-LabTfsEnvironment: AutomatedLabCore/en-us/Test-LabTfsEnvironment.md
- Unblock-LabSources: AutomatedLabCore/en-us/Unblock-LabSources.md
- Undo-LabHostRemoting: AutomatedLabCore/en-us/Undo-LabHostRemoting.md
- Uninstall-LabRdsCertificate: AutomatedLabCore/en-us/Uninstall-LabRdsCertificate.md
- UnInstall-LabSshKnownHost: AutomatedLabCore/en-us/UnInstall-LabSshKnownHost.md
- Uninstall-LabWindowsFeature: AutomatedLabCore/en-us/Uninstall-LabWindowsFeature.md
- Uninstall-LWAzureWindowsFeature: AutomatedLabWorker/en-us/Uninstall-LWAzureWindowsFeature.md
- Uninstall-LWHypervWindowsFeature: AutomatedLabWorker/en-us/Uninstall-LWHypervWindowsFeature.md
- Update-LabAzureSettings: AutomatedLabCore/en-us/Update-LabAzureSettings.md
- Update-LabBaseImage: AutomatedLabCore/en-us/Update-LabBaseImage.md
- Update-LabIsoImage: AutomatedLabCore/en-us/Update-LabIsoImage.md
- Update-LabSnippet: AutomatedLab.Recipe/en-us/Update-LabSnippet.md
- Update-LabSysinternalsTools: AutomatedLabCore/en-us/Update-LabSysinternalsTools.md
- Wait-LabADReady: AutomatedLabCore/en-us/Wait-LabADReady.md
- Wait-LabVM: AutomatedLabCore/en-us/Wait-LabVM.md
- Wait-LabVMRestart: AutomatedLabCore/en-us/Wait-LabVMRestart.md
- Wait-LabVMShutdown: AutomatedLabCore/en-us/Wait-LabVMShutdown.md
- Wait-LWAzureRestartVM: AutomatedLabWorker/en-us/Wait-LWAzureRestartVM.md
- Wait-LWHypervVMRestart: AutomatedLabWorker/en-us/Wait-LWHypervVMRestart.md
- Wait-LWLabJob: AutomatedLabWorker/en-us/Wait-LWLabJob.md
- Wait-LWVMWareRestartVM: AutomatedLabWorker/en-us/Wait-LWVMWareRestartVM.md
- Write-LogError: PSLog/en-us/Write-LogError.md
- Write-LogFunctionEntry: PSLog/en-us/Write-LogFunctionEntry.md
- Write-LogFunctionExit: PSLog/en-us/Write-LogFunctionExit.md
- Write-LogFunctionExitWithError: PSLog/en-us/Write-LogFunctionExitWithError.md
- Write-ProgressIndicator: PSLog/en-us/Write-ProgressIndicator.md
- Write-ProgressIndicatorEnd: PSLog/en-us/Write-ProgressIndicatorEnd.md
- Write-ScreenInfo: PSLog/en-us/Write-ScreenInfo.md
site_name: AutomatedLab - Lab automation from users for users
theme: readthedocs
edit_uri: edit/master/Help/
docs_dir: Help
site_author: Jan-Hendrik Peters, Raimund Andree
``` | /content/code_sandbox/mkdocs.yml | yaml | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 11,280 |
```powershell
@{
ModuleVersion = '1.0.0'
Author = 'Raimund Andree, Per Pedersen, Jan-Hendrik Peters'
CompanyName = 'AutomatedLab Team'
CompatiblePSEditions = 'Core', 'Desktop'
Description = 'This module uses pluggable providers to send various kinds of notifications for AutomatedLab'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
CLRVersion = '4.0'
RootModule = 'AutomatedLabNotifications.psm1'
GUID = '35afbbac-f3d2-49a1-ad6e-abb89aac4349'
FunctionsToExport = 'Send-ALNotification'
CmdletsToExport = @()
VariablesToExport = @()
AliasesToExport = @()
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('LabNotifications' , 'IFTTT', 'Toast', 'Lab', 'LabAutomation', 'HyperV', 'Azure')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
``` | /content/code_sandbox/AutomatedLabNotifications/AutomatedLabNotifications.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 318 |
```powershell
foreach ($file in Get-ChildItem -Path "$PSScriptRoot/internal/functions" -Filter *.ps1 -Recurse) {
. $file.FullName
}
foreach ($file in Get-ChildItem -Path "$PSScriptRoot/functions" -Filter *.ps1 -Recurse) {
. $file.FullName
}
foreach ($file in Get-ChildItem -Path "$PSScriptRoot/internal/scripts" -Filter *.ps1 -Recurse) {
. $file.FullName
}
``` | /content/code_sandbox/AutomatedLabNotifications/AutomatedLabNotifications.psm1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 108 |
```powershell
function Send-ALNotification
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Activity,
[Parameter(Mandatory = $true)]
[System.String]
$Message,
[ValidateSet('Toast','Ifttt','Mail','Voice')]
[string[]]
$Provider
)
begin
{
$lab = Get-Lab -ErrorAction SilentlyContinue
if (-not $lab)
{
Write-PSFMessage -Message "No lab data available. Skipping notification."
}
}
process
{
if (-not $lab)
{
return
}
foreach ($selectedProvider in $Provider)
{
$functionName = "Send-AL$($selectedProvider)Notification"
Write-PSFMessage $functionName
&$functionName -Activity $Activity -Message $Message
}
}
}
``` | /content/code_sandbox/AutomatedLabNotifications/functions/Send-ALNotification.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 198 |
```powershell
function Send-ALIftttNotification
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Activity,
[Parameter(Mandatory = $true)]
[System.String]
$Message
)
$lab = Get-Lab -ErrorAction SilentlyContinue
$key = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Ifttt.Key
$eventName = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Ifttt.EventName
$messageBody = @{
value1 = $lab.Name + " on " + $lab.DefaultVirtualizationEngine
value2 = $Activity
value3 = $Message
}
try
{
$request = Invoke-WebRequest -Method Post -Uri path_to_url -ContentType "application/json" -Body ($messageBody | ConvertTo-Json -Compress) -ErrorAction Stop
if (-not $request.StatusCode -eq 200)
{
Write-PSFMessage -Message "Notification to IFTTT could not be sent with event $eventName. Status code was $($request.StatusCode)"
}
}
catch
{
Write-PSFMessage -Message "Notification to IFTTT could not be sent with event $eventName."
}
}
``` | /content/code_sandbox/AutomatedLabNotifications/internal/functions/Send-ALIftttNotification.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 271 |
```powershell
function Send-ALMailNotification
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Activity,
[Parameter(Mandatory = $true)]
[System.String]
$Message
)
$lab = Get-Lab
$body = @"
Dear recipient,
Lab $($lab.Name) on $($Lab.DefaultVirtualizationEngine)logged activity "$Activity" with the following message:
$Message
"@
$mailParameters = @{
SmtpServer = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Mail.SmtpServer
From = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Mail.From
CC = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Mail.CC
To = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Mail.To
Priority = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Mail.Priority
Port = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Mail.Port
Body = $body
Subject = "AutomatedLab notification: $($lab.Name) $Activity"
}
Send-MailMessage @mailParameters
}
``` | /content/code_sandbox/AutomatedLabNotifications/internal/functions/Send-ALMailNotification.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 240 |
```powershell
function Send-ALVoiceNotification
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Activity,
[Parameter(Mandatory = $true)]
[System.String]
$Message
)
$lab = Get-Lab
$culture = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Voice.Culture
$gender = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Voice.Gender
try
{
Add-Type -AssemblyName System.Speech -ErrorAction Stop
}
catch
{
return
}
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
try
{
$synth.SelectVoiceByHints($gender, 30, $null, $culture)
}
catch {return}
if (-not $synth.Voice)
{
Write-PSFMessage -Level Warning -Message ('No voice installed for culture {0} and gender {1}' -f $culture, $gender)
return;
}
$synth.SetOutputToDefaultAudioDevice()
$text = "
Hi {4}!
AutomatedLab has a new message for you!
Deployment of {0} on {1} entered status {2}. Message {3}.
Live long and prosper.
" -f $lab.Name, $lab.DefaultVirtualizationEngine, $Activity, $Message, $env:USERNAME
$synth.Speak($Text)
$synth.Dispose()
}
``` | /content/code_sandbox/AutomatedLabNotifications/internal/functions/Send-ALVoiceNotification.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 329 |
```powershell
function Send-ALToastNotification
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Activity,
[Parameter(Mandatory = $true)]
[System.String]
$Message
)
$isFullGui = $true # Client
if (Get-Item 'HKLM:\software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels' -ErrorAction SilentlyContinue)
{
[bool]$core = [int](Get-ItemProperty 'HKLM:\software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels' -Name ServerCore -ErrorAction SilentlyContinue).ServerCore
[bool]$guimgmt = [int](Get-ItemProperty 'HKLM:\software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels' -Name Server-Gui-Mgmt -ErrorAction SilentlyContinue).'Server-Gui-Mgmt'
[bool]$guimgmtshell = [int](Get-ItemProperty 'HKLM:\software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels' -Name Server-Gui-Shell -ErrorAction SilentlyContinue).'Server-Gui-Shell'
$isFullGui = $core -and $guimgmt -and $guimgmtshell
}
if ($PSVersionTable.BuildVersion -lt 6.3 -or -not $isFullGui)
{
Write-PSFMessage -Message 'No toasts for OS version < 6.3 or Server Core'
return
}
# Hardcoded toaster from PowerShell - no custom Toast providers after 1709
$toastProvider = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe"
$imageLocation = Get-LabConfigurationItem -Name Notifications.NotificationProviders.Toast.Image
$imagePath = "$((Get-LabConfigurationItem -Name LabAppDataRoot))\Assets"
$imageFilePath = Join-Path $imagePath -ChildPath (Split-Path $imageLocation -Leaf)
if (-not (Test-Path -Path $imagePath))
{
[void](New-Item -ItemType Directory -Path $imagePath)
}
if (-not (Test-Path -Path $imageFilePath))
{
$file = Get-LabInternetFile -Uri $imageLocation -Path $imagePath -PassThru
}
$lab = Get-Lab
$template = "<?xml version=`"1.0`" encoding=`"utf-8`"?><toast><visual><binding template=`"ToastGeneric`"><text>{2}</text><text>Deployment of {0} on {1}, current status '{2}'. Message {3}.</text><image src=`"{4}`" placement=`"appLogoOverride`" hint-crop=`"circle`" /></binding></visual></toast>" -f `
$lab.Name, $lab.DefaultVirtualizationEngine, $Activity, $Message, $imageFilePath
try
{
[void]([Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime])
[void]([Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime])
[void]([Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime])
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($template)
$toast = New-Object Windows.UI.Notifications.ToastNotification $xml
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($toastProvider).Show($toast)
}
catch
{
Write-PSFMessage "Error sending toast notification: $($_.Exception.Message)"
}
}
``` | /content/code_sandbox/AutomatedLabNotifications/internal/functions/Send-ALToastNotification.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 820 |
```powershell
@{
RootModule = 'AutomatedLab.psm1'
ModuleVersion = '1.0.0'
CompatiblePSEditions = 'Core', 'Desktop'
GUID = '6ee6d36f-7914-4bf6-9e3b-c0131669e808'
Author = 'Raimund Andree, Per Pedersen, Jan-Hendrik Peters'
CompanyName = 'AutomatedLab Team'
Description = 'Automated lab environments with ease - Linux and Windows, Hyper-V and Azure'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
CLRVersion = '4.0'
ScriptsToProcess = @()
FormatsToProcess = @( )
NestedModules = @( )
RequiredModules = @(
'AutomatedLabCore'
@{ ModuleName = 'AutomatedLab.Common'; ModuleVersion = '2.3.17' }
'AutomatedLab.Recipe'
'AutomatedLab.Ships'
'AutomatedLabDefinition'
'AutomatedLabNotifications'
'AutomatedLabTest'
'AutomatedLabUnattended'
'AutomatedLabWorker'
'PSLog'
'PSFileTransfer'
'HostsFile'
'Pester'
'powershell-yaml'
'PSFramework'
'SHiPS'
)
CmdletsToExport = @()
FunctionsToExport = @( )
AliasesToExport = @( )
FileList = @( )
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('Lab', 'LabAutomation', 'HyperV', 'Azure')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
}
``` | /content/code_sandbox/AutomatedLab/AutomatedLab.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 410 |
```powershell
# Here be dragons
``` | /content/code_sandbox/AutomatedLab/AutomatedLab.psm1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 5 |
```powershell
@{
RootModule = 'AutomatedLabWorker.psm1'
ModuleVersion = '1.0.0'
CompatiblePSEditions = 'Core', 'Desktop'
GUID = '3addac35-cd7a-4bd2-82f5-ab9c83a48246'
Author = 'Raimund Andree, Per Pedersen, Jan-Hendrik Peters'
CompanyName = 'AutomatedLab Team'
Description = 'This module encapsulates all the work activities to prepare the lab'
PowerShellVersion = '5.1'
DotNetFrameworkVersion = '4.0'
FunctionsToExport = @(
'Add-LWAzureLoadBalancedPort',
'Add-LWVMVHDX',
'Checkpoint-LWAzureVM',
'Checkpoint-LWHypervVM',
'Connect-LWAzureLabSourcesDrive',
'Disable-LWAzureAutoShutdown',
'Dismount-LWAzureIsoImage',
'Dismount-LWIsoImage',
'Enable-LWAzureAutoShutdown',
'Enable-LWAzureVMRemoting',
'Enable-LWAzureWinRm',
'Enable-LWHypervVMRemoting',
'Enable-LWVMWareVMRemoting',
'Get-LabAzureLoadBalancedPort',
'Get-LWAzureAutoShutdown',
'Get-LWAzureLoadBalancedPort',
'Get-LWAzureNetworkSwitch',
'Get-LWAzureSku',
'Get-LWAzureVm',
'Get-LWAzureVMConnectionInfo',
'Get-LWAzureVmSize',
'Get-LWAzureVmSnapshot',
'Get-LWAzureVMStatus',
'Get-LWAzureWindowsFeature',
'Get-LWHypervNetworkSwitchDescription',
'Get-LWHypervVM',
'Get-LWHypervVMDescription',
'Get-LWHypervVMSnapshot',
'Get-LWHypervVMStatus',
'Get-LWHypervWindowsFeature',
'Get-LWVMWareNetworkSwitch',
'Get-LWVMWareVMStatus',
'Initialize-LWAzureVM',
'Install-LWAzureWindowsFeature',
'Install-LWHypervWindowsFeature',
'Install-LWLabCAServers',
'Install-LWLabCAServers2008',
'Invoke-LWCommand',
'Mount-LWAzureIsoImage',
'Mount-LWIsoImage',
'New-LabAzureResourceGroupDeployment',
'New-LWAzureLoadBalancer',
'New-LWHypervNetworkSwitch',
'New-LWHypervVM',
'New-LWHypervVMConnectSettingsFile',
'New-LWReferenceVHDX',
'New-LWVHDX',
'New-LWVMWareVM',
'Remove-LWAzureLoadBalancer',
'Remove-LWAzureVM',
'Remove-LWAzureVmSnapshot',
'Remove-LWAzureRecoveryServicesVault',
'Remove-LWHypervVM',
'Remove-LWHypervVMSnapshot',
'Remove-LWNetworkSwitch',
'Remove-LWVHDX',
'Remove-LWVMWareVM',
'Repair-LWHypervNetworkConfig',
'Remove-LWHypervVMConnectSettingsFile',
'Restore-LWAzureVmSnapshot',
'Restore-LWHypervVMSnapshot',
'Save-LWHypervVM',
'Save-LWVMWareVM',
'Set-LWAzureDnsServer',
'Set-LWHypervNetworkSwitchDescription',
'Set-LWHypervVMDescription',
'Start-LWAzureVM',
'Start-LWHypervVM',
'Start-LWVMWareVM',
'Stop-LWAzureVM',
'Stop-LWHypervVM',
'Stop-LWVMWareVM',
'Test-IpInSameSameNetwork',
'Uninstall-LWAzureWindowsFeature',
'Uninstall-LWHypervWindowsFeature',
'Wait-LWAzureRestartVM',
'Wait-LWHypervVMRestart',
'Wait-LWLabJob',
'Wait-LWVMWareRestartVM'
)
RequiredModules = @( )
NestedModules = @( )
FileList = @( )
PrivateData = @{
PSData = @{
Prerelease = ''
Tags = @('LabWorker', 'Lab', 'LabAutomation', 'HyperV', 'Azure')
ProjectUri = 'path_to_url
IconUri = 'path_to_url
ReleaseNotes = ''
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/AutomatedLabWorker.psd1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,003 |
```powershell
function New-LWVHDX
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
#Path to reference VHD
[Parameter(Mandatory = $true)]
[string]$VhdxPath,
#Size of the reference VHD
[Parameter(Mandatory = $true)]
[int]$SizeInGB,
[string]$Label,
[switch]$UseLargeFRS,
[char]$DriveLetter,
[long]$AllocationUnitSize,
[string]$PartitionStyle,
[switch]$SkipInitialize
)
Write-LogFunctionEntry
$PSBoundParameters.Add('ProgressIndicator', 1) #enables progress indicator
$VmDisk = New-VHD -Path $VhdxPath -SizeBytes ($SizeInGB * 1GB) -ErrorAction Stop
Write-ProgressIndicator
Write-PSFMessage "Created VHDX file '$($vmDisk.Path)'"
if ($SkipInitialize)
{
Write-PSFMessage -Message "Skipping the initialization of '$($vmDisk.Path)'"
Write-LogFunctionExit
return
}
$mountedVhd = $VmDisk | Mount-VHD -PassThru
Write-ProgressIndicator
if ($DriveLetter)
{
$Label += "_AL_$DriveLetter"
}
$formatParams = @{
FileSystem = 'NTFS'
NewFileSystemLabel = 'Data'
Force = $true
Confirm = $false
UseLargeFRS = $UseLargeFRS
AllocationUnitSize = $AllocationUnitSize
}
if ($Label)
{
$formatParams.NewFileSystemLabel = $Label
}
$mountedVhd | Initialize-Disk -PartitionStyle $PartitionStyle
$mountedVhd | New-Partition -UseMaximumSize -AssignDriveLetter |
Format-Volume @formatParams |
Out-Null
Write-ProgressIndicator
$VmDisk | Dismount-VHD
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Disks/New-LWVHDX.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 456 |
```powershell
function Remove-LWVHDX
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
#Path to reference VHD
[Parameter(Mandatory = $true)]
[string]$VhdxPath
)
Write-LogFunctionEntry
$VmDisk = Get-VHD -Path $VhdxPath -ErrorAction SilentlyContinue
if (-not $VmDisk)
{
Write-ScreenInfo -Message "VHDX '$VhdxPath' does not exist, cannot remove it" -Type Warning
}
else
{
$VmDisk | Remove-Item
Write-PSFMessage "VHDX '$($vmDisk.Path)' removed"
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Disks/Remove-LWVHDX.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 183 |
```powershell
function New-LWReferenceVHDX
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
#ISO of OS
[Parameter(Mandatory = $true)]
[string]$IsoOsPath,
#Path to reference VHD
[Parameter(Mandatory = $true)]
[string]$ReferenceVhdxPath,
#Path to reference VHD
[Parameter(Mandatory = $true)]
[string]$OsName,
#Real image name in ISO file
[Parameter(Mandatory = $true)]
[string]$ImageName,
#Size of the reference VHD
[Parameter(Mandatory = $true)]
[int]$SizeInGB,
[Parameter(Mandatory = $true)]
[ValidateSet('MBR', 'GPT')]
[string]$PartitionStyle
)
Write-LogFunctionEntry
# Get start time
$start = Get-Date
Write-PSFMessage "Beginning at $start"
try
{
$FDVDenyWriteAccess = (Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -ErrorAction SilentlyContinue).FDVDenyWriteAccess
$imageList = Get-LabAvailableOperatingSystem -Path $IsoOsPath
Write-PSFMessage "The Windows Image list contains $($imageList.Count) items"
Write-PSFMessage "Mounting ISO image '$IsoOsPath'"
[void] (Mount-DiskImage -ImagePath $IsoOsPath)
Write-PSFMessage 'Getting disk image of the ISO'
$isoImage = Get-DiskImage -ImagePath $IsoOsPath | Get-Volume
Write-PSFMessage "Got disk image '$($isoImage.DriveLetter)'"
$isoDrive = "$($isoImage.DriveLetter):"
Write-PSFMessage "OS ISO mounted on drive letter '$isoDrive'"
$image = $imageList | Where-Object OperatingSystemName -eq $OsName
if (-not $image)
{
throw "The specified image ('$OsName') could not be found on the ISO '$(Split-Path -Path $IsoOsPath -Leaf)'. Please specify one of the following values: $($imageList.ImageName -join ', ')"
}
$imageIndex = $image.ImageIndex
Write-PSFMessage "Selected image index '$imageIndex' with name '$($image.ImageName)'"
$vmDisk = New-VHD -Path $ReferenceVhdxPath -SizeBytes ($SizeInGB * 1GB) -ErrorAction Stop
Write-PSFMessage "Created VHDX file '$($vmDisk.Path)'"
Write-ScreenInfo -Message "Creating base image for operating system '$OsName'" -NoNewLine -TaskStart
[void] (Mount-DiskImage -ImagePath $ReferenceVhdxPath)
$vhdDisk = Get-DiskImage -ImagePath $ReferenceVhdxPath | Get-Disk
$vhdDiskNumber = [string]$vhdDisk.Number
Write-PSFMessage "Reference image is on disk number '$vhdDiskNumber'"
Initialize-Disk -Number $vhdDiskNumber -PartitionStyle $PartitionStyle | Out-Null
if ($PartitionStyle -eq 'MBR')
{
if ($FDVDenyWriteAccess) {
Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -Value 0
}
$vhdWindowsDrive = New-Partition -DiskNumber $vhdDiskNumber -UseMaximumSize -IsActive -AssignDriveLetter |
Format-Volume -FileSystem NTFS -NewFileSystemLabel 'System' -Confirm:$false
}
else
{
$vhdRecoveryPartition = New-Partition -DiskNumber $vhdDiskNumber -GptType '{de94bba4-06d1-4d40-a16a-bfd50179d6ac}' -Size 300MB
$vhdRecoveryDrive = $vhdRecoveryPartition | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'Windows RE Tools' -Confirm:$false
$recoveryPartitionNumber = (Get-Disk -Number $vhdDiskNumber | Get-Partition | Where-Object Type -eq Recovery).PartitionNumber
$diskpartCmd = @"
select disk $vhdDiskNumber
select partition $recoveryPartitionNumber
gpt attributes=0x8000000000000001
exit
"@
$diskpartCmd | diskpart.exe | Out-Null
$systemPartition = New-Partition -DiskNumber $vhdDiskNumber -GptType '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}' -Size 100MB
#does not work, seems to be a bug. Using diskpart as a workaround
#$systemPartition | Format-Volume -FileSystem FAT32 -NewFileSystemLabel 'System' -Confirm:$false
$diskpartCmd = @"
select disk $vhdDiskNumber
select partition $($systemPartition.PartitionNumber)
format quick fs=fat32 label=System
exit
"@
$diskpartCmd | diskpart.exe | Out-Null
$reservedPartition = New-Partition -DiskNumber $vhdDiskNumber -GptType '{e3c9e316-0b5c-4db8-817d-f92df00215ae}' -Size 128MB
if ($FDVDenyWriteAccess) {
Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -Value 0
}
$vhdWindowsDrive = New-Partition -DiskNumber $vhdDiskNumber -UseMaximumSize -AssignDriveLetter |
Format-Volume -FileSystem NTFS -NewFileSystemLabel 'System' -Confirm:$false
}
$vhdWindowsVolume = "$($vhdWindowsDrive.DriveLetter):"
Write-PSFMessage "VHD drive '$vhdWindowsDrive', Vhd volume '$vhdWindowsVolume'"
Write-PSFMessage "Disabling Bitlocker Drive Encryption on drive $vhdWindowsVolume"
if (Test-Path -Path C:\Windows\System32\manage-bde.exe)
{
manage-bde.exe -off $vhdWindowsVolume | Out-Null #without this on some devices (for exmaple Surface 3) the VHD was auto-encrypted
}
Write-PSFMessage 'Applying image to the volume...'
$installFilePath = Get-Item -Path "$isoDrive\Sources\install.*" | Where-Object Name -Match '.*\.(esd|wim)'
$job = Start-Job -ScriptBlock {
$output = Dism.exe /English /apply-Image /ImageFile:$using:installFilePath /index:$using:imageIndex /ApplyDir:$using:vhdWindowsVolume\
New-Object PSObject -Property @{
Outout = $output
LastExitCode = $LASTEXITCODE
}
}
$dismResult = Wait-LWLabJob -Job $job -NoDisplay -ProgressIndicator 20 -Timeout 60 -PassThru
if ($dismResult.LastExitCode)
{
throw (New-Object System.ComponentModel.Win32Exception($dismResult.LastExitCode,
"The base image for operating system '$OsName' could not be created. The error is $($dismResult.LastExitCode)"))
}
Start-Sleep -Seconds 10
Write-PSFMessage 'Setting BCDBoot'
if ($PartitionStyle -eq 'MBR')
{
bcdboot.exe $vhdWindowsVolume\Windows /s $vhdWindowsVolume /f BIOS | Out-Null
}
else
{
$possibleDrives = [char[]](65..90)
$drives = (Get-PSDrive -PSProvider FileSystem).Name
$freeDrives = Compare-Object -ReferenceObject $possibleDrives -DifferenceObject $drives | Where-Object { $_.SideIndicator -eq '<=' }
$freeDrive = ($freeDrives | Select-Object -First 1).InputObject
$diskpartCmd = @"
select disk $vhdDiskNumber
select partition $($systemPartition.PartitionNumber)
assign letter=$freeDrive
exit
"@
$diskpartCmd | diskpart.exe | Out-Null
bcdboot.exe $vhdWindowsVolume\Windows /s "$($freeDrive):" /f UEFI | Out-Null
$diskpartCmd = @"
select disk $vhdDiskNumber
select partition $($systemPartition.PartitionNumber)
remove letter=$freeDrive
exit
"@
$diskpartCmd | diskpart.exe | Out-Null
}
}
catch
{
Write-PSFMessage 'Dismounting ISO and new disk'
[void] (Dismount-DiskImage -ImagePath $ReferenceVhdxPath)
[void] (Dismount-DiskImage -ImagePath $IsoOsPath)
Remove-Item -Path $ReferenceVhdxPath -Force #removing as the creation did not succeed
if ($FDVDenyWriteAccess) {
Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -Value $FDVDenyWriteAccess
}
throw $_.Exception
}
Write-PSFMessage 'Dismounting ISO and new disk'
[void] (Dismount-DiskImage -ImagePath $ReferenceVhdxPath)
[void] (Dismount-DiskImage -ImagePath $IsoOsPath)
if ($FDVDenyWriteAccess) {
Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Policies\Microsoft\FVE -Name FDVDenyWriteAccess -Value $FDVDenyWriteAccess
}
Write-ScreenInfo -Message 'Finished creating base image' -TaskEnd
$end = Get-Date
Write-PSFMessage "Runtime: '$($end - $start)'"
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Disks/New-LWReferenceVHDX.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,252 |
```powershell
function Add-LWVMVHDX
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
[Parameter(Mandatory = $true)]
[string]$VMName,
[Parameter(Mandatory = $true)]
[string]$VhdxPath
)
Write-LogFunctionEntry
if (-not (Test-Path -Path $VhdxPath))
{
Write-Error 'VHDX cannot be found'
return
}
$vm = Get-LWHypervVM -Name $VMName -ErrorAction SilentlyContinue
if (-not $vm)
{
Write-Error 'VM cannot be found'
return
}
Add-VMHardDiskDrive -VM $vm -Path $VhdxPath
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Disks/Add-LWVMVHDX.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 195 |
```powershell
function Install-LWLabCAServers2008
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification="Historic cmdlet, will not be updated")]
[Cmdletbinding()]
param (
[Parameter(Mandatory)]
[hashtable]$param
)
Write-LogFunctionEntry
#region - Parameters debug
Write-Debug -Message your_sha256_hash-----------------------'
Write-Debug -Message 'Parameters - Entered Install-LWLabCAServers'
Write-Debug -Message your_sha256_hash-----------------------'
if ($param.GetEnumerator().count)
{
foreach ($key in ($param.GetEnumerator() | Sort-Object -Property Name)) { Write-Debug -message " $($key.key.padright(27)) $($key.value)" }
}
else
{
Write-Debug -message ' No parameters specified'
}
Write-Debug -Message your_sha256_hash-----------------------'
Write-Debug -Message ''
#endregion - Parameters debug
#region ScriptBlock for installation
$caScriptBlock = {
param ($param)
function Install-WebEnrollment
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$CAConfig
)
# check if web enrollment binaries are installed
Import-Module ServerManager
# instanciate COM object
try
{
$EWPSetup = New-Object -ComObject CertOCM.CertSrvSetup.1
}
catch
{
Write-ScreenInfo "Unable to load necessary interfaces. Your Windows Server operating system is not supported!" -Type Warning
return
}
# initialize the object to install only web enrollment
$EWPSetup.InitializeDefaults($false,$true)
try
{
# set required information and install the role
$EWPSetup.SetWebCAInformation($CAConfig)
$EWPSetup.Install()
}
catch
{
$_
return
}
Write-Host "Successfully installed Enrollment Web Pages on local computer!" -ForegroundColor Green
}
Import-Module -Name ServerManager
#region - Check if CA is already installed
Write-Verbose -Message 'Check if ADCS-Cert-Authority is already installed'
if ((Get-WindowsFeature -Name 'ADCS-Cert-Authority').Installed)
{
Write-Verbose -Message 'ADCS-Cert-Authority is already installed. Returning'
Write-Output "A Certificate Authority is already installed on '$($param.ComputerName)'. Skipping installation."
return
}
#endregion
#region - Create CAPolicy file
$caPolicyFileName = "$Env:Windir\CAPolicy.inf"
if (-not (Test-Path -Path $caPolicyFileName))
{
Write-Verbose -Message 'Create CAPolicy.inf file'
Set-Content $caPolicyFileName -Force -Value ';CAPolicy for CA'
Add-Content $caPolicyFileName -Value '; Please replace sample CPS OID with your own OID'
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[Version]'
Add-Content $caPolicyFileName -Value "Signature=`"`$Windows NT`$`" "
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[PolicyStatementExtension]'
Add-Content $caPolicyFileName -Value 'Policies=LegalPolicy'
Add-Content $caPolicyFileName -Value 'Critical=0'
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[LegalPolicy]'
Add-Content $caPolicyFileName -Value 'OID=1.3.6.1.4.1.11.21.43'
Add-Content $caPolicyFileName -Value "Notice=$($param.CpsText)"
Add-Content $caPolicyFileName -Value "URL=$($param.CpsUrl)"
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[Certsrv_Server]'
Add-Content $caPolicyFileName -Value 'ForceUTF8=true'
Add-Content $caPolicyFileName -Value "RenewalKeyLength=$($param.KeyLength)"
Add-Content $caPolicyFileName -Value "RenewalValidityPeriod=$($param.ValidityPeriod)"
Add-Content $caPolicyFileName -Value "RenewalValidityPeriodUnits=$($param.ValidityPeriodUnits)"
Add-Content $caPolicyFileName -Value "CRLPeriod=$($param.CRLPeriod)"
Add-Content $caPolicyFileName -Value "CRLPeriodUnits=$($param.CRLPeriodUnits)"
Add-Content $caPolicyFileName -Value "CRLDeltaPeriod=$($param.CRLDeltaPeriod)"
Add-Content $caPolicyFileName -Value "CRLDeltaPeriodUnits=$($param.CRLDeltaPeriodUnits)"
Add-Content $caPolicyFileName -Value 'EnableKeyCounting=0'
Add-Content $caPolicyFileName -Value 'AlternateSignatureAlgorithm=0'
if ($param.DoNotLoadDefaultTemplates -eq 'True') { Add-Content $caPolicyFileName -Value 'LoadDefaultTemplates=0' }
if ($param.CAType -like '*root*')
{
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[Extensions]'
Add-Content $caPolicyFileName -Value ';Remove CA Version Index'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.21.1='
Add-Content $caPolicyFileName -Value ';Remove CA Hash of previous CA Certificates'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.21.2='
Add-Content $caPolicyFileName -Value ';Remove V1 Certificate Template Information'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.20.2='
Add-Content $caPolicyFileName -Value ';Remove CA of V2 Certificate Template Information'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.21.7='
Add-Content $caPolicyFileName -Value ';Key Usage Attribute set to critical'
Add-Content $caPolicyFileName -Value '2.5.29.15=AwIBBg=='
Add-Content $caPolicyFileName -Value 'Critical=2.5.29.15'
}
if ($param.DebugPref -eq 'Continue')
{
$file = get-content -Path "$Env:Windir\CAPolicy.inf"
Write-Debug -Message 'CApolicy.inf contents:'
foreach ($line in $file)
{
Write-Debug -Message $line
}
}
}
#endregion - Create CAPolicy file
#region - Install CA
$hostOSVersion = [Environment]::OSVersion.Version
if ($hostOSVersion -ge [system.version]'6.2')
{
$InstallFeatures = 'Import-Module -Name ServerManager; Add-WindowsFeature -IncludeManagementTools -Name ADCS-Cert-Authority'
}
else
{
$InstallFeatures = 'Import-Module -Name ServerManager; Add-WindowsFeature -Name ADCS-Cert-Authority'
}
# OCSP not yet supported
#if ($param.InstallOCSP) { $InstallFeatures += ", ADCS-Online-Cert" }
if ($param.InstallWebEnrollment) { $InstallFeatures += ', ADCS-Web-Enrollment' }
Write-Verbose -Message "Install roles and feature using command '$InstallFeatures'"
Invoke-Expression -Command ($InstallFeatures += " -Confirm:`$false") | Out-Null
if ($param.ForestAdminUserName)
{
Write-Verbose -Message "ForestAdminUserName=$($param.ForestAdminUserName), ForestAdminPassword=$($param.ForestAdminPassword)"
Write-Verbose -Message "Adding $($param.ForestAdminUserName) to local administrators group"
Write-Verbose -Message "WinNT:://$($param.ForestAdminUserName.replace('\', '/'))"
$localGroup = ([ADSI]'WinNT://./Administrators,group')
$localGroup.psbase.Invoke('Add', ([ADSI]"WinNT://$($param.ForestAdminUserName.replace('\', '/'))").path)
$forestAdminCred = (New-Object System.Management.Automation.PSCredential($param.ForestAdminUserName, ($param.ForestAdminPassword | ConvertTo-SecureString -AsPlainText -Force)))
}
else
{
Write-Verbose -Message 'No ForestAdminUserName!'
}
try
{
$CASetup = New-Object -ComObject CertOCM.CertSrvSetup.1
}
catch
{
Write-Verbose -Message "Unable to load necessary interfaces. Operating system is not supported for PKI."
return
}
try
{
$CASetup.InitializeDefaults($true, $false)
}
catch
{
Write-Verbose -Message "Cannot initialize setup binaries!"
}
$CATypesByVal = @{}
$CATypesByName.keys | ForEach-Object {$CATypesByVal.Add($CATypesByName[$_],$_)}
$CAPRopertyByName = @{"CAType"=0
"CAKeyInfo"=1
"Interactive"=2
"ValidityPeriodUnits"=5
"ValidityPeriod"=6
"ExpirationDate"=7
"PreserveDataBase"=8
"DBDirectory"=9
"Logdirectory"=10
"ParentCAMachine"=12
"ParentCAName"=13
"RequestFile"=14
"WebCAMachine"=15
"WebCAName"=16}
$CAPRopertyByVal = @{}
$CAPRopertyByName.keys | ForEach-Object `
{
$CAPRopertyByVal.Add($CAPRopertyByName[$_],$_)
}
$ValidityUnitsByName = @{"years" = 6}
$ValidityUnitsByVal = @{6 = "years"}
$ofs = ", "
#key length and hashing algorithm verification
$CAKey = $CASetup.GetCASetupProperty(1)
if ($param.CryptoProviderName -ne "")
{
if ($CASetup.GetProviderNameList() -notcontains $param.CryptoProviderName)
{
# TODO add available CryptoProviderName list
Write-Host "Specified CSP '$param.CryptoProviderName' is not valid!"
}
else
{
$CAKey.ProviderName = $param.CryptoProviderName
}
}
else
{
$CAKey.ProviderName = "RSA#Microsoft Software Key Storage Provider"
}
Write-Verbose -Message "ProviderName = '$($CAKey.ProviderName)'"
if ($param.KeyLength -ne 0)
{
if ($CASetup.GetKeyLengthList($param.CryptoProviderName).Length -eq 1)
{
$CAKey.Length = $CASetup.GetKeyLengthList($param.CryptoProviderName)[0]
}
else
{
if ($CASetup.GetKeyLengthList($param.CryptoProviderName) -notcontains $param.KeyLength)
{
Write-Host "The specified key length '$KeyLength' is not supported by the selected CryptoProviderName '$param.CryptoProviderName'"
Write-Host "The following key lengths are supported by this CryptoProviderName:"
foreach ($provider in ($CASetup.GetKeyLengthList($param.CryptoProviderName)))
{
Write-Host " $provider"
}
}
$CAKey.Length = $param.KeyLength
}
}
Write-Verbose -Message "KeyLength = '$($CAKey.KeyLength)'"
if ($param.HashAlgorithmName -ne "")
{
if ($CASetup.GetHashAlgorithmList($param.CryptoProviderName) -notcontains $param.HashAlgorithmName)
{
Write-ScreenInfo -Message "The specified hash algorithm is not supported by the selected CryptoProviderName '$param.CryptoProviderName'"
Write-ScreenInfo -Message "The following hash algorithms are supported by this CryptoProviderName:" -Type Error
foreach ($algorithm in ($CASetup.GetHashAlgorithmList($param.CryptoProviderName)))
{
Write-ScreenInfo -Message " $algorithm" -Type Error
}
}
$CAKey.HashAlgorithm = $param.HashAlgorithmName
}
$CASetup.SetCASetupProperty(1,$CAKey)
Write-Verbose -Message "Hash Algorithm = '$($CAKey.HashAlgorithm)'"
if ($param.CAType)
{
$SupportedTypes = $CASetup.GetSupportedCATypes()
$CATypesByName = @{'EnterpriseRootCA'=0;'EnterpriseSubordinateCA'=1;'StandaloneRootCA'=3;'StandaloneSubordinateCA'=4}
$SelectedType = $CATypesByName[$param.CAType]
if ($SupportedTypes -notcontains $SelectedType)
{
Write-Host "Selected CA type: '$CAType' is not supported by current Windows Server installation."
Write-Host "The following CA types are supported by this installation:"
#foreach ($caType in (
{
#Write-ScreenInfo -Message "$([int[]]$CASetup.GetSupportedCATypes() | %{$CATypesByVal[$_]})
}
}
}
else
{
$CASetup.SetCASetupProperty($CAPRopertyByName.CAType,$SelectedType)
}
Write-Verbose -Message "CAType = '$($param.CAType)'"
if ($SelectedType -eq 0 -or $SelectedType -eq 3 -and $param.ValidityPeriodUnits -ne 0)
{
try
{
$CASetup.SetCASetupProperty(6,([int]$param.ValidityPeriodUnits))
}
catch
{
Write-Host "The specified CA certificate validity period '$($param.ValidityPeriodUnits)' is invalid."
}
}
Write-Verbose -Message "ValidityPeriod = '$($param.ValidityPeriodUnits)'"
$DN = New-Object -ComObject X509Enrollment.CX500DistinguishedName
# validate X500 name format
try
{
$DN.Encode("CN=$($param.CACommonName)",0x0)
}
catch
{
Write-Host "Specified CA name or CA name suffix is not correct X.500 Distinguished Name."
}
$CASetup.SetCADistinguishedName("CN=$($param.CACommonName)", $true, $true, $true)
Write-Verbose -Message "CADistinguishedName = 'CN=$($param.CACommonName)'"
if ($CASetup.GetCASetupProperty(0) -eq 1 -and $param.ParentCA)
{
[void]($param.ParentCA -match "^(.+)\\(.+)$")
try
{
$CASetup.SetParentCAInformation($param.ParentCA)
}
catch
{
Write-Host "The specified parent CA information '$param.ParentCA' is incorrect. Make sure if parent CA information is correct (you must specify existing CA) and is supplied in a 'CAComputerName\CASanitizedName' form."
}
}
Write-Verbose -Message "PArentCA = 'CN=$($param.CACommonName)'"
if ($param.DatabaseDirectory -eq '')
{
$param.DatabaseDirectory = 'C:\Windows\system32\CertLog'
}
Write-Verbose -Message "DatabaseDirectory = '$($param.DatabaseDirectory)'"
if ($param.LogDirectory -eq '')
{
$param.LogDirectory = 'C:\Windows\system32\CertLog'
}
Write-Verbose -Message "LogDirectory = '$($param.LogDirectory)'"
if ($param.DatabaseDirectory -ne "" -and $param.LogDirectory -ne "")
{
try
{
$CASetup.SetDatabaseInformation($param.DatabaseDirectory,$param.LogDirectory,$null,$OverwriteExisting)
}
catch
{
Write-Verbose -Message 'Specified path to either database directory or log directory is invalid.'
}
}
try
{
Write-Verbose -Message 'Installing Certification Authority'
$CASetup.Install()
if ($CASetup.GetCASetupProperty(0) -eq 1)
{
$CASName = (Get-ItemProperty HKLM:\System\CurrentControlSet\Services\CertSvc\Configuration).Active
$SetupStatus = (Get-ItemProperty HKLM:\System\CurrentControlSet\Services\CertSvc\Configuration\$CASName).SetupStatus
$RequestID = (Get-ItemProperty HKLM:\System\CurrentControlSet\Services\CertSvc\Configuration\$CASName).RequestID
}
Write-Verbose -Message 'Certification Authority role is successfully installed'
}
catch
{
Write-Error $_ -ErrorAction Stop
}
if ($param.ForestAdminUserName)
{
Write-Verbose -Message "Removing $($param.ForestAdminUserName) to local administrators group"
$localGroup = ([ADSI]'WinNT://./Administrators,group')
$localGroup.psbase.Invoke('Remove', ([ADSI]"WinNT://$($param.ForestAdminUserName.replace('\', '/'))").path)
}
if ($param.InstallWebEnrollment)
{
Write-Verbose -Message 'InstallWebRole is True, hence setting InstallWebRole to True'
$param.InstallWebRole = $true
}
if ($param.InstallWebRole)
{
Write-Verbose -Message 'Check if web role is already installed'
if (!((Get-WindowsFeature -Name 'web-server').Installed))
{
Write-Verbose -Message 'Web role is NOT already installed. Installing it now.'
Add-WindowsFeature -Name 'Web-Server' -IncludeManagementTools
#Allow "+" characters in URL for supporting delta CRLs
#Set-WebConfiguration -Filter system.webServer/security/requestFiltering -PSPath 'IIS:\sites\Default Web Site' -Value @{allowDoubleEscaping=$true}
}
}
if ($param.InstallWebEnrollment)
{
Write-Verbose -Message 'Installing Web Enrollment service'
Install-WebEnrollment "$($param.ComputerName)\$($param.CACommonName)"
}
#endregion - Install CA
#region - Configure IIS virtual directories
if ($param.UseHTTPAia)
{
#New-WebVirtualDirectory -Site 'Default Web Site' -Name Aia -PhysicalPath 'C:\Windows\System32\CertSrv\CertEnroll' | Out-Null
#New-WebVirtualDirectory -Site 'Default Web Site' -Name Cdp -PhysicalPath 'C:\Windows\System32\CertSrv\CertEnroll' | Out-Null
}
#endregion - Configure IIS virtual directories
#region - Configure CA
function Invoke-CustomExpression
{
param ($Command)
Invoke-Expression -Command $command
Write-Verbose -Message $command
}
#Declare configuration NC
if ($param.CAType -like 'Enterprise*')
{
$lDAPname = ''
foreach ($part in ($param.DomainName.split('.')))
{
$lDAPname += ",DC=$part"
}
Invoke-CustomExpression -Command "certutil.exe -setreg ""CA\DSConfigDN"" ""CN=Configuration$lDAPname"""
}
#Apply the required CDP Extension URLs
$command = "certutil.exe -setreg CA\CRLPublicationURLs ""1:$($Env:WinDir)\system32\CertSrv\CertEnroll\%3%8%9.crl"
if ($param.UseLDAPCRL) { $command += '\n11:ldap:///CN=%7%8,CN=%2,CN=CDP,CN=Public Key Services,CN=Services,%6%10' }
if ($param.UseHTTPCRL) { $command += "\n2:$($param.CDPHTTPURL01)/%3%8%9.crl" }
if ($param.AIAHTTPURL01UploadLocation) { $command += "\n1:$($param.AIAHTTPURL01UploadLocation)/%3%8%9.crl" }
$command += '"'
Invoke-CustomExpression -Command $command
#Apply the required AIA Extension URLs
$command = "certutil.exe -setreg CA\CACertPublicationURLs ""1:$($Env:WinDir)\system3\CertSrv\CertEnroll\%1_%3%4.crt"
if ($param.UseLDAPAia) { $command += '\n3:ldap:///CN=%7,CN=AIA,CN=Public Key Services,CN=Services,%6%11' }
if ($param.UseHTTPAia) { $command += "\n2:$($param.AIAHTTPURL01)/%1_%3%4.crt" }
if ($param.AIAHTTPURL01UploadLocation) { $command += "\n1:$($param.AIAHTTPURL01UploadLocation)/%3%8%9.crl" }
$command += '"'
Invoke-CustomExpression -Command $command
#Define default maximum certificate lifetime for issued certificates
Invoke-CustomExpression -Command "certutil.exe -setreg ca\ValidityPeriodUnits $($param.CertsValidityPeriodUnits)"
Invoke-CustomExpression -Command "certutil.exe -setreg ca\ValidityPeriod ""$($param.CertsValidityPeriod)"""
#Define CRL Publication Intervals
Invoke-CustomExpression -Command "certutil.exe -setreg CA\CRLPeriodUnits $($param.CRLPeriodUnits)"
Invoke-CustomExpression -Command "certutil.exe -setreg CA\CRLPeriod ""$($param.CRLPeriod)"""
#Define CRL Overlap
Invoke-CustomExpression -Command "certutil.exe -setreg CA\CRLOverlapUnits $($param.CRLOverlapUnits)"
Invoke-CustomExpression -Command "certutil.exe -setreg CA\CRLOverlapPeriod ""$($param.CRLOverlapPeriod)"""
#Define Delta CRL
Invoke-CustomExpression -Command "certutil.exe -setreg CA\CRLDeltaUnits $($param.CRLDeltaPeriodUnits)"
Invoke-CustomExpression -Command "certutil.exe -setreg CA\CRLDeltaPeriod ""$($param.CRLDeltaPeriod)"""
#Enable Auditing Logging
Invoke-CustomExpression -Command 'certutil.exe -setreg CA\Auditfilter 0x7F'
#Enable UTF-8 Encoding
Invoke-CustomExpression -Command 'certutil.exe -setreg ca\forceteletex +0x20'
if ($param.CAType -like '*root*')
{
#Disable Discrete Signatures in Subordinate Certificates (WinXP KB968730)
Invoke-CustomExpression -Command 'certutil.exe -setreg CA\csp\AlternateSignatureAlgorithm 0'
#Force digital signature removal in KU for cert issuance (see also kb888180)
Invoke-CustomExpression -Command 'certutil.exe -setreg policy\EditFlags -EDITF_ADDOLDKEYUSAGE'
#Enable SAN
Invoke-CustomExpression -Command 'certutil.exe -setreg policy\EditFlags +EDITF_ATTRIBUTESUBJECTALTNAME2'
#Configure policy module to automatically issue certificates when requested
Invoke-CustomExpression -Command 'certutil.exe -setreg ca\PolicyModules\CertificateAuthority_MicrosoftDefault.Policy\RequestDisposition 1'
}
#If CA is Root CA and Sub CAs are present, disable (do not publish) templates (except SubCA template)
if ($param.DoNotLoadDefaultTemplates)
{
Invoke-CustomExpression -Command 'certutil.exe -SetCATemplates +SubCA'
}
#endregion - Configure CA
#region - Restart of CA
if ((Get-Service -Name 'CertSvc').Status -eq 'Running')
{
Write-Verbose -Message 'Stopping ADCS Service'
$totalretries = 5
$retries = 0
do
{
Stop-Service -Name 'CertSvc' -ErrorAction SilentlyContinue
if ((Get-Service -Name 'CertSvc').Status -ne 'Stopped')
{
$retries++
Start-Sleep -Seconds 1
}
}
until (((Get-Service -Name 'CertSvc').Status -eq 'Stopped') -or ($retries -ge $totalretries))
if ((Get-Service -Name 'CertSvc').Status -eq 'Stopped')
{
Write-Verbose -Message 'ADCS service is now stopped'
}
else
{
Write-Error -Message 'Could not stop ADCS Service after several retries'
return
}
}
Write-Verbose -Message 'Starting ADCS Service now'
$totalretries = 5
$retries = 0
do
{
Start-Service -Name 'CertSvc' -ErrorAction SilentlyContinue
if ((Get-Service -Name 'CertSvc').Status -ne 'Running')
{
$retries++
Start-Sleep -Seconds 1
}
}
until (((Get-Service -Name 'CertSvc').Status -eq 'Running') -or ($retries -ge $totalretries))
if ((Get-Service -Name 'CertSvc').Status -eq 'Running')
{
Write-Verbose -Message 'ADCS service is now started'
}
else
{
Write-Error -Message 'Could not start ADCS Service after several retries'
return
}
#endregion - Restart of CA
Write-Verbose -Message 'Waiting for admin interface to be ready'
$totalretries = 10
$retries = 0
do
{
$result = Invoke-Expression -Command "certutil.exe -pingadmin .\$($param.CACommonName)"
if (!($result | Where-Object { $_ -like '*interface is alive*' }))
{
$retries++
Write-Verbose -Message "Admin interface not ready. Check $retries of $totalretries"
if ($retries -lt $totalretries) { Start-Sleep -Seconds 10 }
}
}
until (($result | Where-Object { $_ -like '*interface is alive*' }) -or ($retries -ge $totalretries))
if ($result | Where-Object { $_ -like '*interface is alive*' })
{
Write-Verbose -Message 'Admin interface is now ready'
}
else
{
Write-Error -Message 'Admin interface was not ready after several retries'
return
}
#region - Issue of CRL
Start-Sleep -Seconds 2
Invoke-Expression -Command 'certutil.exe -crl' | Out-Null
$totalretries = 12
$retries = 0
do
{
Start-Sleep -Seconds 5
$retries++
}
until ((Get-ChildItem "$env:systemroot\system32\CertSrv\CertEnroll\*.crl") -or ($retries -ge $totalretries))
#endregion - Issue of CRL
if (($param.CAType -like 'Enterprise*') -and ($param.DoNotLoadDefaultTemplates)) { Invoke-Expression 'certutil.exe -SetCATemplates +SubCA' }
}
#endregion
Write-PSFMessage -Message "Performing installation of $($param.CAType) on '$($param.ComputerName)'"
$cred = (New-Object System.Management.Automation.PSCredential($param.UserName, ($param.Password | ConvertTo-SecureString -AsPlainText -Force)))
$caSession = New-LabPSSession -ComputerName $param.ComputerName
$Job = Invoke-Command -Session $caSession -Scriptblock $caScriptBlock -ArgumentList $param -AsJob -JobName "Install CA on '$($param.Computername)'" -Verbose
$Job
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/ADCS/Install-LWLabCAServers2008.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 6,221 |
```powershell
function Disable-LWAzureAutoShutdown
{
param
(
[string[]]
$ComputerName,
[switch]
$Wait
)
$lab = Get-Lab -ErrorAction Stop
$labVms = Get-AzVm -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
if ($ComputerName)
{
$labVms = $labVms | Where-Object Name -in $ComputerName
}
$resourceIdString = '{0}/providers/microsoft.devtestlab/schedules/shutdown-computevm-' -f $lab.AzureSettings.DefaultResourceGroup.ResourceId
$jobs = foreach ($vm in $labVms)
{
Remove-AzResource -ResourceId ("$($resourceIdString)$($vm.Name)") -Force -ErrorAction SilentlyContinue -AsJob
}
if ($jobs -and $Wait.IsPresent)
{
$null = $jobs | Wait-Job
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Disable-LWAzureAutoShutdown.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 211 |
```powershell
function Get-LWAzureVmSize
{
[Cmdletbinding()]
param
(
[Parameter(Mandatory)]
[AutomatedLab.Machine]$Machine
)
$lab = Get-Lab
if ($machine.AzureRoleSize)
{
$roleSize = $lab.AzureSettings.RoleSizes |
Where-Object { $_.Name -eq $machine.AzureRoleSize }
Write-PSFMessage -Message "Using specified role size of '$($roleSize.Name)'"
}
elseif ($machine.AzureProperties.RoleSize)
{
$roleSize = $lab.AzureSettings.RoleSizes |
Where-Object { $_.Name -eq $machine.AzureProperties.RoleSize }
Write-PSFMessage -Message "Using specified role size of '$($roleSize.Name)'"
}
elseif ($machine.AzureProperties.UseAllRoleSizes)
{
$DefaultAzureRoleSize = Get-LabConfigurationItem -Name DefaultAzureRoleSize
$roleSize = $lab.AzureSettings.RoleSizes |
Where-Object { $_.MemoryInMB -ge $machine.Memory -and $_.NumberOfCores -ge $machine.Processors -and $machine.Disks.Count -le $_.MaxDataDiskCount } |
Sort-Object -Property MemoryInMB, NumberOfCores |
Select-Object -First 1
Write-PSFMessage -Message "Using specified role size of '$($roleSize.InstanceSize)'. VM was configured to all role sizes but constrained to role size '$DefaultAzureRoleSize' by psd1 file"
}
else
{
$pattern = switch ($lab.AzureSettings.DefaultRoleSize)
{
'A' { '^Standard_A\d{1,2}(_v\d{1,3})|Basic_A\d{1,2})' }
'AS' { '^Standard_AS\d{1,2}(_v\d{1,3})' }
'AC' { '^Standard_AC\d{1,2}(_v\d{1,3})' }
'D' { '^Standard_D\d{1,2}(_v\d{1,3})' }
'DS' { '^Standard_DS\d{1,2}(_v\d{1,3})' }
'DC' { '^Standard_DC\d{1,2}(_v\d{1,3})' }
"E" { '^Standard_E\d{1,2}(_v\d{1,3})' }
"ES" { '^Standard_ES\d{1,2}(_v\d{1,3})' }
"EC" { '^Standard_EC\d{1,2}(_v\d{1,3})' }
'F' { '^Standard_F\d{1,2}(_v\d{1,3})' }
'FS' { '^Standard_FS\d{1,2}(_v\d{1,3})' }
'FC' { '^Standard_FC\d{1,2}(_v\d{1,3})' }
'G' { '^Standard_G\d{1,2}(_v\d{1,3})' }
'GS' { '^Standard_GS\d{1,2}(_v\d{1,3})' }
'GC' { '^Standard_GC\d{1,2}(_v\d{1,3})' }
'H' { '^Standard_H\d{1,2}(_v\d{1,3})' }
'HS' { '^Standard_HS\d{1,2}(_v\d{1,3})' }
'HC' { '^Standard_HC\d{1,2}(_v\d{1,3})' }
'L' { '^Standard_L\d{1,2}(_v\d{1,3})' }
'LS' { '^Standard_LS\d{1,2}(_v\d{1,3})' }
'LC' { '^Standard_LC\d{1,2}(_v\d{1,3})' }
'N' { '^Standard_N\d{1,2}(_v\d{1,3})' }
'NS' { '^Standard_NS\d{1,2}(_v\d{1,3})' }
'NC' { '^Standard_NC\d{1,2}(_v\d{1,3})' }
default { '^(Standard_A\d{1,2}(_v\d{1,3})|Basic_A\d{1,2})' }
}
$roleSize = $lab.AzureSettings.RoleSizes |
Where-Object { $_.Name -Match $pattern -and $_.Name -notlike '*promo*' } |
Where-Object { $_.MemoryInMB -ge ($machine.Memory / 1MB) -and $_.NumberOfCores -ge $machine.Processors } |
Sort-Object -Property MemoryInMB, NumberOfCores, @{ Expression = { if ($_.Name -match '.+_v(?<Version>\d{1,2})') { $Matches.Version } }; Ascending = $false } |
Select-Object -First 1
Write-PSFMessage -Message "Using specified role size of '$($roleSize.Name)' out of role sizes '$pattern'"
}
$roleSize
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Get-LWAzureVmSize.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,139 |
```powershell
function Install-LWLabCAServers
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification="Historic cmdlet, will not be updated")]
param (
[Parameter(Mandatory = $true)][string]$ComputerName,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$DomainName,
[Parameter(Mandatory = $true)][string]$UserName,
[Parameter(Mandatory = $true)][string]$Password,
[Parameter(Mandatory = $false)][string]$ForestAdminUserName,
[Parameter(Mandatory = $false)][string]$ForestAdminPassword,
[Parameter(Mandatory = $false)][string]$ParentCA,
[Parameter(Mandatory = $false)][string]$ParentCALogicalName,
[Parameter(Mandatory = $true)][string]$CACommonName,
[Parameter(Mandatory = $true)][string]$CAType,
[Parameter(Mandatory = $true)][string]$KeyLength,
[Parameter(Mandatory = $true)][string]$CryptoProviderName,
[Parameter(Mandatory = $true)][string]$HashAlgorithmName,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$DatabaseDirectory,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$LogDirectory,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$CpsUrl,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$CpsText,
[Parameter(Mandatory = $true)][boolean]$UseLDAPAIA,
[Parameter(Mandatory = $true)][boolean]$UseHTTPAia,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$AIAHTTPURL01,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$AiaHttpUrl02,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$AIAHTTPURL01UploadLocation,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$AiaHttpUrl02UploadLocation,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$OCSPHttpUrl01,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$OCSPHttpUrl02,
[Parameter(Mandatory = $true)][boolean]$UseLDAPCRL,
[Parameter(Mandatory = $true)][boolean]$UseHTTPCRL,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$CDPHTTPURL01,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$CDPHTTPURL02,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$CDPHTTPURL01UploadLocation,
[Parameter(Mandatory = $true)][AllowEmptyString()][string]$CDPHTTPURL02UploadLocation,
[Parameter(Mandatory = $true)][boolean]$InstallOCSP,
[Parameter(Mandatory = $false)][string]$ValidityPeriod,
[Parameter(Mandatory = $false)][int]$ValidityPeriodUnits,
[Parameter(Mandatory = $true)][string]$CRLPeriod,
[Parameter(Mandatory = $true)][int]$CRLPeriodUnits,
[Parameter(Mandatory = $true)][string]$CRLOverlapPeriod,
[Parameter(Mandatory = $true)][int]$CRLOverlapUnits,
[Parameter(Mandatory = $true)][string]$CRLDeltaPeriod,
[Parameter(Mandatory = $true)][int]$CRLDeltaPeriodUnits,
[Parameter(Mandatory = $true)][string]$CertsValidityPeriod,
[Parameter(Mandatory = $true)][int]$CertsValidityPeriodUnits,
[Parameter(Mandatory = $true)][boolean]$InstallWebEnrollment,
[Parameter(Mandatory = $true)][boolean]$InstallWebRole,
[Parameter(Mandatory = $true)][boolean]$DoNotLoadDefaultTemplates,
[Parameter(Mandatory = $false)][int]$PreDelaySeconds
)
Write-LogFunctionEntry
Install-LabWindowsFeature -ComputerName $ComputerName -FeatureName RSAT-AD-Tools -IncludeAllSubFeature -NoDisplay
#region - Create parameter table
$param = @{ }
$param.Add('ComputerName', $ComputerName)
$param.add('DomainName', $DomainName)
$param.Add('UserName', $UserName)
$param.Add('Password', $Password)
$param.Add('ForestAdminUserName', $ForestAdminUserName)
$param.Add('ForestAdminPassword', $ForestAdminPassword)
$param.Add('CACommonName', $CACommonName)
$param.Add('CAType', $CAType)
$param.Add('CryptoProviderName', $CryptoProviderName)
$param.Add('HashAlgorithmName', $HashAlgorithmName)
$param.Add('KeyLength', $KeyLength)
$param.Add('CertEnrollFolderPath', $CertEnrollFolderPath)
$param.Add('DatabaseDirectory', $DatabaseDirectory)
$param.Add('LogDirectory', $LogDirectory)
$param.Add('CpsUrl', $CpsUrl)
$param.Add('CpsText', """$($CpsText)""")
$param.Add('UseLDAPAIA', $UseLDAPAIA)
$param.Add('UseHTTPAia', $UseHTTPAia)
$param.Add('AIAHTTPURL01', $AIAHTTPURL01)
$param.Add('AiaHttpUrl02', $AiaHttpUrl02)
$param.Add('AIAHTTPURL01UploadLocation', $AIAHTTPURL01UploadLocation)
$param.Add('AiaHttpUrl02UploadLocation', $AiaHttpUrl02UploadLocation)
$param.Add('OCSPHttpUrl01', $OCSPHttpUrl01)
$param.Add('OCSPHttpUrl02', $OCSPHttpUrl02)
$param.Add('UseLDAPCRL', $UseLDAPCRL)
$param.Add('UseHTTPCRL', $UseHTTPCRL)
$param.Add('CDPHTTPURL01', $CDPHTTPURL01)
$param.Add('CDPHTTPURL02', $CDPHTTPURL02)
$param.Add('CDPHTTPURL01UploadLocation', $CDPHTTPURL01UploadLocation)
$param.Add('CDPHTTPURL02UploadLocation', $CDPHTTPURL02UploadLocation)
$param.Add('InstallOCSP', $InstallOCSP)
$param.Add('ValidityPeriod', $ValidityPeriod)
$param.Add('ValidityPeriodUnits', $ValidityPeriodUnits)
$param.Add('CRLPeriod', $CRLPeriod)
$param.Add('CRLPeriodUnits', $CRLPeriodUnits)
$param.Add('CRLOverlapPeriod', $CRLOverlapPeriod)
$param.Add('CRLOverlapUnits', $CRLOverlapUnits)
$param.Add('CRLDeltaPeriod', $CRLDeltaPeriod)
$param.Add('CRLDeltaPeriodUnits', $CRLDeltaPeriodUnits)
$param.Add('CertsValidityPeriod', $CertsValidityPeriod)
$param.Add('CertsValidityPeriodUnits', $CertsValidityPeriodUnits)
$param.Add('InstallWebEnrollment', $InstallWebEnrollment)
$param.Add('InstallWebRole', $InstallWebRole)
$param.Add('DoNotLoadDefaultTemplates', $DoNotLoadDefaultTemplates)
#For Subordinate CAs only
if ($ParentCA) { $param.add('ParentCA', $ParentCA) }
if ($ParentCALogicalname) { $param.add('ParentCALogicalname', $ParentCALogicalName) }
$param.Add('PreDelaySeconds', $PreDelaySeconds)
#endregion - Create parameter table
#region - Parameters debug
Write-Debug -Message your_sha256_hash-----------------------'
Write-Debug -Message 'Parameters - Entered Install-LWLabCAServers'
Write-Debug -Message your_sha256_hash-----------------------'
if ($param.GetEnumerator().count)
{
foreach ($key in ($param.GetEnumerator() | Sort-Object -Property Name)) { Write-Debug -message " $($key.key.padright(27)) $($key.value)" }
}
else
{
Write-Debug -message ' No parameters specified'
}
Write-Debug -Message your_sha256_hash-----------------------'
Write-Debug -Message ''
#endregion - Parameters debug
#region ScriptBlock for installation
$caScriptBlock = {
param ($param)
$param | Export-Clixml C:\DeployDebug\CaParams.xml
#Make semi-sure that each install of CA server is not done at the same time
Start-Sleep -Seconds $param.PreDelaySeconds
Import-Module -Name ServerManager
#region - Check if CA is already installed
if ((Get-WindowsFeature -Name 'ADCS-Cert-Authority').Installed)
{
Write-Output "A Certificate Authority is already installed on '$($param.ComputerName)'. Skipping installation."
return
}
#endregion
#region - Create CAPolicy file
$caPolicyFileName = "$Env:Windir\CAPolicy.inf"
if (-not (Test-Path -Path $caPolicyFileName))
{
Write-Verbose -Message 'Create CAPolicy.inf file'
Set-Content $caPolicyFileName -Force -Value ';CAPolicy for CA'
Add-Content $caPolicyFileName -Value '; Please replace sample CPS OID with your own OID'
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[Version]'
Add-Content $caPolicyFileName -Value "Signature=`"`$Windows NT`$`" "
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[PolicyStatementExtension]'
Add-Content $caPolicyFileName -Value 'Policies=LegalPolicy'
Add-Content $caPolicyFileName -Value 'Critical=0'
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[LegalPolicy]'
Add-Content $caPolicyFileName -Value 'OID=1.3.6.1.4.1.11.21.43'
Add-Content $caPolicyFileName -Value "Notice=$($param.CpsText)"
Add-Content $caPolicyFileName -Value "URL=$($param.CpsUrl)"
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[Certsrv_Server]'
Add-Content $caPolicyFileName -Value 'ForceUTF8=true'
Add-Content $caPolicyFileName -Value "RenewalKeyLength=$($param.KeyLength)"
Add-Content $caPolicyFileName -Value "RenewalValidityPeriod=$($param.ValidityPeriod)"
Add-Content $caPolicyFileName -Value "RenewalValidityPeriodUnits=$($param.ValidityPeriodUnits)"
Add-Content $caPolicyFileName -Value "CRLPeriod=$($param.CRLPeriod)"
Add-Content $caPolicyFileName -Value "CRLPeriodUnits=$($param.CRLPeriodUnits)"
Add-Content $caPolicyFileName -Value "CRLDeltaPeriod=$($param.CRLDeltaPeriod)"
Add-Content $caPolicyFileName -Value "CRLDeltaPeriodUnits=$($param.CRLDeltaPeriodUnits)"
Add-Content $caPolicyFileName -Value 'EnableKeyCounting=0'
Add-Content $caPolicyFileName -Value 'AlternateSignatureAlgorithm=0'
if ($param.DoNotLoadDefaultTemplates) { Add-Content $caPolicyFileName -Value 'LoadDefaultTemplates=0' }
if ($param.CAType -like '*root*')
{
Add-Content $caPolicyFileName -Value ''
Add-Content $caPolicyFileName -Value '[Extensions]'
Add-Content $caPolicyFileName -Value ';Remove CA Version Index'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.21.1='
Add-Content $caPolicyFileName -Value ';Remove CA Hash of previous CA Certificates'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.21.2='
Add-Content $caPolicyFileName -Value ';Remove V1 Certificate Template Information'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.20.2='
Add-Content $caPolicyFileName -Value ';Remove CA of V2 Certificate Template Information'
Add-Content $caPolicyFileName -Value '1.3.6.1.4.1.311.21.7='
Add-Content $caPolicyFileName -Value ';Key Usage Attribute set to critical'
Add-Content $caPolicyFileName -Value '2.5.29.15=AwIBBg=='
Add-Content $caPolicyFileName -Value 'Critical=2.5.29.15'
}
if ($param.DebugPref -eq 'Continue')
{
$file = get-content -Path "$Env:Windir\CAPolicy.inf"
Write-Debug -Message 'CApolicy.inf contents:'
foreach ($line in $file)
{
Write-Debug -Message $line
}
}
}
#endregion - Create CAPolicy file
#region - Install CA
$hostOSVersion = [Environment]::OSVersion.Version
if ($hostOSVersion -ge [system.version]'6.2')
{
$InstallFeatures = 'Import-Module -Name ServerManager; Add-WindowsFeature -IncludeManagementTools -Name ADCS-Cert-Authority'
}
else
{
$InstallFeatures = 'Import-Module -Name ServerManager; Add-WindowsFeature -Name ADCS-Cert-Authority'
}
# OCSP not yet supported
#if ($param.InstallOCSP) { $InstallFeatures += ", ADCS-Online-Cert" }
if ($param.InstallWebEnrollment) { $InstallFeatures += ', ADCS-Web-Enrollment' }
if ($param.ForestAdminUserName)
{
Write-Verbose -Message "ForestAdminUserName=$($param.ForestAdminUserName), ForestAdminPassword=$($param.ForestAdminPassword)"
if ($param.DebugPref -eq 'Continue')
{
Write-Verbose -Message "Adding $($param.ForestAdminUserName) to local administrators group"
Write-Verbose -Message "WinNT:://$($param.ForestAdminUserName.replace('\', '/'))"
}
$localGroup = ([ADSI]'WinNT://./Administrators,group')
$localGroup.psbase.Invoke('Add', ([ADSI]"WinNT://$($param.ForestAdminUserName.replace('\', '/'))").path)
Write-Verbose -Message "Check 2c -create credential of ""$($param.ForestAdminUserName)"" and ""$($param.ForestAdminPassword)"""
$forestAdminCred = (New-Object System.Management.Automation.PSCredential($param.ForestAdminUserName, ($param.ForestAdminPassword | ConvertTo-SecureString -AsPlainText -Force)))
}
else
{
Write-Verbose -Message 'No ForestAdminUserName!'
}
Write-Verbose -Message 'Installing roles and features now'
Write-Verbose -Message "Command: $InstallFeatures"
Invoke-Expression -Command ($InstallFeatures += " -Confirm:`$false") | Out-Null
Write-Verbose -Message 'Installing ADCS now'
$installCommand = 'Install-AdcsCertificationAuthority '
$installCommand += "-CACommonName ""$($param.CACommonName)"" "
$installCommand += "-CAType $($param.CAType) "
$installCommand += "-KeyLength $($param.KeyLength) "
$installCommand += "-CryptoProviderName ""$($param.CryptoProviderName)"" "
$installCommand += "-HashAlgorithmName ""$($param.HashAlgorithmName)"" "
$installCommand += '-OverwriteExistingKey '
$installCommand += '-OverwriteExistingDatabase '
$installCommand += '-Force '
$installCommand += '-Confirm:$false '
if ($forestAdminCred) { $installCommand += '-Credential $forestAdminCred ' }
if ($param.DatabaseDirectory) { $installCommand += "-DatabaseDirectory $($param.DatabaseDirectory) " }
if ($param.LogDirectory) { $installCommand += "-LogDirectory $($param.LogDirectory) " }
if ($param.CAType -like '*root*')
{
$installCommand += "-ValidityPeriod $($param.ValidityPeriod) "
$installCommand += "-ValidityPeriodUnits $($param.ValidityPeriodUnits) "
}
else
{
$installCommand += "-ParentCA $($param.ParentCA)`\$($param.ParentCALogicalName) "
}
$installCommand += ' | Out-Null'
if ($param.DebugPref -eq 'Continue')
{
Write-Debug -Message 'Install command:'
Write-Debug -Message $installCommand
Set-Content -Path 'C:\debug-CAinst.txt' -value $installCommand
}
Invoke-Expression -Command $installCommand
if ($param.ForestAdminUserName)
{
if ($param.DebugPref -eq 'Continue')
{
Write-Debug -Message "Removing $($param.ForestAdminUserName) to local administrators group"
}
$localGroup = ([ADSI]'WinNT://./Administrators,group')
$localGroup.psbase.Invoke('Remove', ([ADSI]"WinNT://$($param.ForestAdminUserName.replace('\', '/'))").path)
}
if ($param.InstallWebEnrollment)
{
Write-Verbose -Message 'Installing Web Enrollment service now'
Install-ADCSWebEnrollment -Confirm:$False | Out-Null
}
if ($param.InstallWebRole)
{
if (!(Get-WindowsFeature -Name 'web-server'))
{
Add-WindowsFeature -Name 'Web-Server' -IncludeManagementTools
#Allow "+" characters in URL for supporting delta CRLs
Set-WebConfiguration -Filter system.webServer/security/requestFiltering -PSPath 'IIS:\sites\Default Web Site' -Value @{allowDoubleEscaping=$true}
}
}
#endregion - Install CA
#region - Configure IIS virtual directories
if ($param.UseHTTPAia)
{
New-WebVirtualDirectory -Site 'Default Web Site' -Name Aia -PhysicalPath 'C:\Windows\System32\CertSrv\CertEnroll' | Out-Null
New-WebVirtualDirectory -Site 'Default Web Site' -Name Cdp -PhysicalPath 'C:\Windows\System32\CertSrv\CertEnroll' | Out-Null
}
#endregion - Configure IIS virtual directories
#region - Configure OCSP
<# OCSP not yet supported
if ($InstallOCSP)
{
Write-Verbose -Message "Installing Online Responder"
Install-ADCSOnlineResponder -Force | Out-Null
}
#>
#endregion - Configure OCSP
#region - Configure CA
function Invoke-CustomExpression
{
param ($Command)
Write-Host $command
Invoke-Expression -Command $command
}
#Declare configuration NC
if ($param.CAType -like 'Enterprise*')
{
$lDAPname = ''
foreach ($part in ($param.DomainName.split('.')))
{
$lDAPname += ",DC=$part"
}
Invoke-CustomExpression -Command "certutil -setreg CA\DSConfigDN ""CN=Configuration$lDAPname"""
}
#Apply the required CDP Extension URLs
$command = "certutil -setreg CA\CRLPublicationURLs ""1:$($Env:WinDir)\system32\CertSrv\CertEnroll\%3%8%9.crl"
if ($param.UseLDAPCRL) { $command += '\n11:ldap:///CN=%7%8,CN=%2,CN=CDP,CN=Public Key Services,CN=Services,%6%10' }
if ($param.UseHTTPCRL) { $command += "\n2:$($param.CDPHTTPURL01)/%3%8%9.crl" }
if ($param.CDPHTTPURL01UploadLocation) { $command += "\n1:$($param.CDPHTTPURL01UploadLocation)/%3%8%9.crl" }
$command += '"'
Invoke-CustomExpression -Command $command
#Apply the required AIA Extension URLs
$command = "certutil -setreg CA\CACertPublicationURLs ""1:$($Env:WinDir)\system3\CertSrv\CertEnroll\%1_%3%4.crt"
if ($param.UseLDAPAia) { $command += '\n3:ldap:///CN=%7,CN=AIA,CN=Public Key Services,CN=Services,%6%11' }
if ($param.UseHTTPAia) { $command += "\n2:$($param.AIAHTTPURL01)/%1_%3%4.crt" }
if ($param.AIAHTTPURL01UploadLocation) { $command += "\n1:$($param.AIAHTTPURL01UploadLocation)/%3%8%9.crl" }
<# OCSP not yet supported
if ($param.InstallOCSP -and $param.OCSPHttpUrl01) { $Line += "\n34:$($param.OCSPHttpUrl01)" }
if ($param.InstallOCSP -and $param.OCSPHttpUrl02) { $Line += "\n34:$($param.OCSPHttpUrl02)" }
#>
$command += '"'
Invoke-CustomExpression -Command $command
#Define default maximum certificate lifetime for issued certificates
Invoke-CustomExpression -Command "certutil -setreg ca\ValidityPeriodUnits $($param.CertsValidityPeriodUnits)"
Invoke-CustomExpression -Command "certutil -setreg ca\ValidityPeriod ""$($param.CertsValidityPeriod)"""
#Define CRL Publication Intervals
Invoke-CustomExpression -Command "certutil -setreg CA\CRLPeriodUnits $($param.CRLPeriodUnits)"
Invoke-CustomExpression -Command "certutil -setreg CA\CRLPeriod ""$($param.CRLPeriod)"""
#Define CRL Overlap
Invoke-CustomExpression -Command "certutil -setreg CA\CRLOverlapUnits $($param.CRLOverlapUnits)"
Invoke-CustomExpression -Command "certutil -setreg CA\CRLOverlapPeriod ""$($param.CRLOverlapPeriod)"""
#Define Delta CRL
Invoke-CustomExpression -Command "certutil -setreg CA\CRLDeltaUnits $($param.CRLDeltaPeriodUnits)"
Invoke-CustomExpression -Command "certutil -setreg CA\CRLDeltaPeriod ""$($param.CRLDeltaPeriod)"""
#Enable Auditing Logging
Invoke-CustomExpression -Command 'certutil -setreg CA\Auditfilter 0x7F'
#Enable UTF-8 Encoding
Invoke-CustomExpression -Command 'certutil -setreg ca\forceteletex +0x20'
if ($param.CAType -like '*root*')
{
#Disable Discrete Signatures in Subordinate Certificates (WinXP KB968730)
Invoke-CustomExpression -Command 'certutil -setreg CA\csp\AlternateSignatureAlgorithm 0'
#Force digital signature removal in KU for cert issuance (see also kb888180)
Invoke-CustomExpression -Command 'certutil -setreg policy\EditFlags -EDITF_ADDOLDKEYUSAGE'
#Enable SAN
Invoke-CustomExpression -Command 'certutil -setreg policy\EditFlags +EDITF_ATTRIBUTESUBJECTALTNAME2'
#Configure policy module to automatically issue certificates when requested
Invoke-CustomExpression -Command 'certutil -setreg ca\PolicyModules\CertificateAuthority_MicrosoftDefault.Policy\RequestDisposition 1'
}
#If CA is Root CA and Sub CAs are present, disable (do not publish) templates (except SubCA template)
if ($param.DoNotLoadDefaultTemplates)
{
Invoke-CustomExpression -Command 'certutil -SetCATemplates +SubCA'
}
#endregion - Configure CA
#region - Restart of CA
if ((Get-Service -Name 'CertSvc').Status -eq 'Running')
{
Write-Verbose -Message 'Stopping ADCS Service'
$totalretries = 5
$retries = 0
do
{
Stop-Service -Name 'CertSvc' -ErrorAction SilentlyContinue
if ((Get-Service -Name 'CertSvc').Status -ne 'Stopped')
{
$retries++
Start-Sleep -Seconds 1
}
}
until (((Get-Service -Name 'CertSvc').Status -eq 'Stopped') -or ($retries -ge $totalretries))
if ((Get-Service -Name 'CertSvc').Status -eq 'Stopped')
{
Write-Verbose -Message 'ADCS service is now stopped'
}
else
{
Write-Error -Message 'Could not stop ADCS Service after several retries'
return
}
}
Write-Verbose -Message 'Starting ADCS Service now'
$totalretries = 5
$retries = 0
do
{
Start-Service -Name 'CertSvc' -ErrorAction SilentlyContinue
if ((Get-Service -Name 'CertSvc').Status -ne 'Running')
{
$retries++
Start-Sleep -Seconds 1
}
}
until (((Get-Service -Name 'CertSvc').Status -eq 'Running') -or ($retries -ge $totalretries))
if ((Get-Service -Name 'CertSvc').Status -eq 'Running')
{
Write-Verbose -Message 'ADCS service is now started'
}
else
{
Write-Error -Message 'Could not start ADCS Service after several retries'
return
}
#endregion - Restart of CA
Write-Verbose -Message 'Waiting for admin interface to be ready'
$totalretries = 10
$retries = 0
do
{
$result = Invoke-Expression -Command "certutil -pingadmin .\$($param.CACommonName)"
if (!($result | Where-Object { $_ -like '*interface is alive*' }))
{
$retries++
Write-Verbose -Message "Admin interface not ready. Check $retries of $totalretries"
if ($retries -lt $totalretries) { Start-Sleep -Seconds 10 }
}
}
until (($result | Where-Object { $_ -like '*interface is alive*' }) -or ($retries -ge $totalretries))
if ($result | Where-Object { $_ -like '*interface is alive*' })
{
Write-Verbose -Message 'Admin interface is now ready'
}
else
{
Write-Error -Message 'Admin interface was not ready after several retries'
return
}
#region - Issue of CRL
Start-Sleep -Seconds 2
Invoke-Expression -Command 'certutil -crl' | Out-Null
$totalretries = 12
$retries = 0
do
{
Start-Sleep -Seconds 5
$retries++
}
until ((Get-ChildItem "$env:systemroot\system32\CertSrv\CertEnroll\*.crl") -or ($retries -ge $totalretries))
#endregion - Issue of CRL
if (($param.CAType -like 'Enterprise*') -and ($param.DoNotLoadDefaultTemplates)) { Invoke-Expression 'certutil -SetCATemplates +SubCA' }
}
#endregion
Write-PSFMessage -Message "Performing installation of $($param.CAType) on '$($param.ComputerName)'"
$job = Invoke-LabCommand -ActivityName "Install CA on '$($param.Computername)'" -ComputerName $param.ComputerName`
-Scriptblock $caScriptBlock -ArgumentList $param -NoDisplay -AsJob -PassThru
$job
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/ADCS/Install-LWLabCAServers.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 6,214 |
```powershell
function Remove-LWAzureRecoveryServicesVault
{
[CmdletBinding()]
param
(
[int]
$RetryCount = 0
)
$lab = Get-Lab -ErrorAction SilentlyContinue
if (-not $lab) { return }
$rsVault = Get-AzResource -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -ResourceType Microsoft.RecoveryServices/vaults -ErrorAction SilentlyContinue
if (-not $rsVault) { return }
if (-not (Get-Module -ListAvailable -Name Az.RecoveryServices | Where-Object Version -ge '5.3.0'))
{
try
{
Install-Module -Force -Name Az.RecoveryServices -Repository PSGallery -MinimumVersion 5.3.0 -ErrorAction Stop
}
catch
{
Write-ScreenInfo -Type Error -Message "Unable to install Az.RecoveryServices, 5.3.0+. Please delete your RecoveryServices Vault $($rsVault.Id) yourself."
return
}
}
Write-LogFunctionEntry
Write-ScreenInfo -Message "Removing recovery services vault $($rsVault.Id) in $($rsVault.ResourceGroupName) so that the resource group can be deleted properly. This takes a while."
$vaultToDelete = Get-AzRecoveryServicesVault -Name $rsVault.ResourceName -ResourceGroupName $rsVault.ResourceGroupName
$null = Set-AzRecoveryServicesAsrVaultContext -Vault $vaultToDelete
$null = Set-AzRecoveryServicesVaultProperty -Vault $vaultToDelete.ID -SoftDeleteFeatureState Disable #disable soft delete
$containerSoftDelete = Get-AzRecoveryServicesBackupItem -BackupManagementType AzureVM -WorkloadType AzureVM -VaultId $vaultToDelete.ID | Where-Object { $_.DeleteState -eq "ToBeDeleted" } #fetch backup items in soft delete state
foreach ($softitem in $containerSoftDelete)
{
$null = Undo-AzRecoveryServicesBackupItemDeletion -Item $softitem -VaultId $vaultToDelete.ID -Force #undelete items in soft delete state
}
if ((Get-Command Set-AzRecoveryServicesVaultProperty).Parameters.ContainsKey('DisableHybridBackupSecurityFeature'))
{
$null = Set-AzRecoveryServicesVaultProperty -VaultId $vaultToDelete.ID -DisableHybridBackupSecurityFeature $true
}
#Fetch all protected items and servers
# Collection of try/catches since some enum values might be invalid
$backupItemsVM = try { Get-AzRecoveryServicesBackupItem -BackupManagementType AzureVM -WorkloadType AzureVM -VaultId $vaultToDelete.ID -ErrorAction Stop } catch {}
$backupItemsSQL = try { Get-AzRecoveryServicesBackupItem -BackupManagementType AzureWorkload -WorkloadType MSSQL -VaultId $vaultToDelete.ID -ErrorAction Stop } catch {}
$backupItemsAFS = try { Get-AzRecoveryServicesBackupItem -BackupManagementType AzureStorage -WorkloadType AzureFiles -VaultId $vaultToDelete.ID -ErrorAction Stop } catch {}
$backupItemsSAP = try { Get-AzRecoveryServicesBackupItem -BackupManagementType AzureWorkload -WorkloadType SAPHanaDatabase -VaultId $vaultToDelete.ID -ErrorAction Stop } catch {}
$backupContainersSQL = try { Get-AzRecoveryServicesBackupContainer -ContainerType AzureVMAppContainer -Status Registered -VaultId $vaultToDelete.ID -ErrorAction Stop | Where-Object { $_.ExtendedInfo.WorkloadType -eq "SQL" } } catch {}
$protectableItemsSQL = try { Get-AzRecoveryServicesBackupProtectableItem -WorkloadType MSSQL -VaultId $vaultToDelete.ID -ErrorAction Stop | Where-Object { $_.IsAutoProtected -eq $true } } catch {}
$backupContainersSAP = try { Get-AzRecoveryServicesBackupContainer -ContainerType AzureVMAppContainer -Status Registered -VaultId $vaultToDelete.ID -ErrorAction Stop | Where-Object { $_.ExtendedInfo.WorkloadType -eq "SAPHana" } } catch {}
$StorageAccounts = try { Get-AzRecoveryServicesBackupContainer -ContainerType AzureStorage -Status Registered -VaultId $vaultToDelete.ID -ErrorAction Stop } catch {}
$backupServersMARS = try { Get-AzRecoveryServicesBackupContainer -ContainerType "Windows" -BackupManagementType MAB -VaultId $vaultToDelete.ID -ErrorAction Stop } catch {}
$backupServersMABS = try { Get-AzRecoveryServicesBackupManagementServer -VaultId $vaultToDelete.ID -ErrorAction Stop | Where-Object { $_.BackupManagementType -eq "AzureBackupServer" } } catch {}
$backupServersDPM = try { Get-AzRecoveryServicesBackupManagementServer -VaultId $vaultToDelete.ID -ErrorAction Stop | Where-Object { $_.BackupManagementType -eq "SCDPM" } } catch {}
$pvtendpoints = try { Get-AzPrivateEndpointConnection -PrivateLinkResourceId $vaultToDelete.ID -ErrorAction Stop } catch {}
$pool = New-RunspacePool -Variable (Get-Variable vaultToDelete) -ThrottleLimit 20
$jobs = [system.Collections.ArrayList]::new()
foreach ($item in $backupItemsVM)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Disable-AzRecoveryServicesBackupProtection -Item $item -VaultId $vaultToDelete.ID -RemoveRecoveryPoints -Force } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupItemsSQL)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Disable-AzRecoveryServicesBackupProtection -Item $item -VaultId $vaultToDelete.ID -RemoveRecoveryPoints -Force } -RunspacePool $pool -Argument $item))
}
foreach ($item in $protectableItems)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Disable-AzRecoveryServicesBackupAutoProtection -BackupManagementType AzureWorkload -WorkloadType MSSQL -InputItem $item -VaultId $vaultToDelete.ID } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupContainersSQL)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Unregister-AzRecoveryServicesBackupContainer -Container $item -Force -VaultId $vaultToDelete.ID } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupItemsSAP)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Disable-AzRecoveryServicesBackupProtection -Item $item -VaultId $vaultToDelete.ID -RemoveRecoveryPoints -Force } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupContainersSAP)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Unregister-AzRecoveryServicesBackupContainer -Container $item -Force -VaultId $vaultToDelete.ID } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupItemsAFS)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Disable-AzRecoveryServicesBackupProtection -Item $item -VaultId $vaultToDelete.ID -RemoveRecoveryPoints -Force } -RunspacePool $pool -Argument $item))
}
foreach ($item in $StorageAccounts)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Unregister-AzRecoveryServicesBackupContainer -container $item -Force -VaultId $vaultToDelete.ID } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupServersMARS)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Unregister-AzRecoveryServicesBackupContainer -Container $item -Force -VaultId $vaultToDelete.ID } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupServersMABS)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Unregister-AzRecoveryServicesBackupManagementServer -AzureRmBackupManagementServer $item -VaultId $vaultToDelete.ID } -RunspacePool $pool -Argument $item))
}
foreach ($item in $backupServersDPM)
{
$null = $jobs.Add((Start-RunspaceJob -ScriptBlock { param ($item) Unregister-AzRecoveryServicesBackupManagementServer -AzureRmBackupManagementServer $item -VaultId $vaultToDelete.ID } -RunspacePool $pool -Argument $item))
}
$null = Wait-RunspaceJob -RunspaceJob $jobs
Remove-RunspacePool -RunspacePool $pool
#Deletion of ASR Items
$fabricObjects = Get-AzRecoveryServicesAsrFabric
# First DisableDR all VMs.
foreach ($fabricObject in $fabricObjects)
{
$containerObjects = Get-AzRecoveryServicesAsrProtectionContainer -Fabric $fabricObject -ErrorAction SilentlyContinue
foreach ($containerObject in $containerObjects)
{
$protectedItems = Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $containerObject -ErrorAction SilentlyContinue
# DisableDR all protected items
foreach ($protectedItem in $protectedItems)
{
$null = Remove-AzRecoveryServicesAsrReplicationProtectedItem -InputObject $protectedItem -Force
}
$containerMappings = Get-AzRecoveryServicesAsrProtectionContainerMapping -ProtectionContainer $containerObject
# Remove all Container Mappings
foreach ($containerMapping in $containerMappings)
{
$null = Remove-AzRecoveryServicesAsrProtectionContainerMapping -ProtectionContainerMapping $containerMapping -Force
}
}
$networkObjects = Get-AzRecoveryServicesAsrNetwork -Fabric $fabricObject
foreach ($networkObject in $networkObjects)
{
#Get the PrimaryNetwork
$PrimaryNetwork = Get-AzRecoveryServicesAsrNetwork -Fabric $fabricObject -FriendlyName $networkObject
$NetworkMappings = Get-AzRecoveryServicesAsrNetworkMapping -Network $PrimaryNetwork
foreach ($networkMappingObject in $NetworkMappings)
{
#Get the Neetwork Mappings
$NetworkMapping = Get-AzRecoveryServicesAsrNetworkMapping -Name $networkMappingObject.Name -Network $PrimaryNetwork
$null = Remove-AzRecoveryServicesAsrNetworkMapping -InputObject $NetworkMapping
}
}
# Remove Fabric
$null = Remove-AzRecoveryServicesAsrFabric -InputObject $fabricObject -Force
}
foreach ($item in $pvtendpoints)
{
$penamesplit = $item.Name.Split(".")
$pename = $penamesplit[0]
$null = Remove-AzPrivateEndpointConnection -ResourceId $item.PrivateEndpoint.Id -Force #remove private endpoint connections
$null = Remove-AzPrivateEndpoint -Name $pename -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -Force #remove private endpoints
}
try
{
$null = Remove-AzRecoveryServicesVault -Vault $vaultToDelete -Confirm:$false -ErrorAction Stop
}
catch
{
if ($RetryCount -le 2)
{
Remove-LWAzureRecoveryServicesVault -RetryCount ($RetryCount + 1)
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Remove-LWAzureRecoveryServicesVault.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 2,571 |
```powershell
function Get-LWAzureVMStatus
{
param (
[Parameter(Mandatory)]
[string[]]$ComputerName
)
Test-LabHostConnected -Throw -Quiet
#required to suporess verbose messages, warnings and errors
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$result = @{ }
$azureVms = Get-LWAzureVm @PSBoundParameters
$resourceGroups = (Get-LabVM -IncludeLinux).AzureConnectionInfo.ResourceGroupName | Select-Object -Unique
$azureVms = $azureVms | Where-Object { $_.Name -in $ComputerName -and $_.ResourceGroupName -in $resourceGroups }
$vmTable = @{ }
Get-LabVm -IncludeLinux | Where-Object FriendlyName -in $ComputerName | ForEach-Object { $vmTable[$_.FriendlyName] = $_.Name }
foreach ($azureVm in $azureVms)
{
$vmName = if ($vmTable[$azureVm.Name]) { $vmTable[$azureVm.Name] } else { $azureVm.Name }
if ($azureVm.PowerState -eq 'VM running')
{
$result.Add($vmName, 'Started')
}
elseif ($azureVm.PowerState -eq 'VM stopped' -or $azureVm.PowerState -eq 'VM deallocated')
{
$result.Add($vmName, 'Stopped')
}
else
{
$result.Add($vmName, 'Unknown')
}
}
$result
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Get-LWAzureVMStatus.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 373 |
```powershell
function Mount-LWAzureIsoImage
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification = "Not relevant, used in Invoke-LabCommand")]
[CmdletBinding()]
param
(
[Parameter(Mandatory, Position = 0)]
[string[]]
$ComputerName,
[Parameter(Mandatory, Position = 1)]
[string]
$IsoPath,
[switch]$PassThru
)
Test-LabHostConnected -Throw -Quiet
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$azureIsoPath = $IsoPath -replace '/', '\' -replace 'https:'
# ISO file should already exist on Azure storage share, as it was initially retrieved from there as well.
# Path is local (usually Azure Stack which has no storage file shares)
if (-not (Test-LabPathIsOnLabAzureLabSourcesStorage -Path $azureIsoPath))
{
Write-ScreenInfo -type Info -Message "Copying $azureIsoPath to $($ComputerName -join ',')"
Copy-LabFileItem -Path $azureIsoPath -ComputerName $ComputerName -DestinationFolderPath C:\ALMounts
$result = Invoke-LabCommand -ActivityName "Mounting $(Split-Path $azureIsoPath -Leaf) on $($ComputerName -join ',')" -ComputerName $ComputerName -ScriptBlock {
$drive = Mount-DiskImage -ImagePath C:\ALMounts\$(Split-Path -Leaf -Path $azureIsoPath) -StorageType ISO -PassThru | Get-Volume
$drive | Add-Member -MemberType NoteProperty -Name DriveLetter -Value ($drive.CimInstanceProperties.Item('DriveLetter').Value + ":") -Force
$drive | Add-Member -MemberType NoteProperty -Name InternalComputerName -Value $env:COMPUTERNAME -Force
$drive | Select-Object -Property *
} -Variable (Get-Variable azureIsoPath) -PassThru:$PassThru.IsPresent
if ($PassThru.IsPresent) { return $result } else { return }
}
Invoke-LabCommand -ActivityName "Mounting $(Split-Path $azureIsoPath -Leaf) on $($ComputerName -join ',')" -ComputerName $ComputerName -ScriptBlock {
if (-not (Test-Path -Path $azureIsoPath))
{
throw "'$azureIsoPath' is not accessible."
}
$drive = Mount-DiskImage -ImagePath $azureIsoPath -StorageType ISO -PassThru | Get-Volume
$drive | Add-Member -MemberType NoteProperty -Name DriveLetter -Value ($drive.CimInstanceProperties.Item('DriveLetter').Value + ":") -Force
$drive | Add-Member -MemberType NoteProperty -Name InternalComputerName -Value $env:COMPUTERNAME -Force
$drive | Select-Object -Property *
} -ArgumentList $azureIsoPath -Variable (Get-Variable -Name azureIsoPath) -PassThru:$PassThru
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Mount-LWAzureIsoImage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 669 |
```powershell
function Remove-LWAzureVmSnapshot
{
[Cmdletbinding()]
Param
(
[Parameter(Mandatory, ParameterSetName = 'BySnapshotName')]
[Parameter(Mandatory, ParameterSetName = 'AllSnapshots')]
[string[]]$ComputerName,
[Parameter(Mandatory, ParameterSetName = 'BySnapshotName')]
[string]$SnapshotName,
[Parameter(ParameterSetName = 'AllSnapshots')]
[switch]$All
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$lab = Get-Lab
$snapshots = Get-AzSnapshot -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -ErrorAction SilentlyContinue
if ($PSCmdlet.ParameterSetName -eq 'BySnapshotName')
{
$snapshotsToRemove = $ComputerName.Foreach( { '{0}_{1}' -f $_, $SnapshotName })
$snapshots = $snapshots | Where-Object -Property Name -in $snapshotsToRemove
}
$null = $snapshots | Remove-AzSnapshot -Force -Confirm:$false
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Remove-LWAzureVmSnapshot.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 246 |
```powershell
function Connect-LWAzureLabSourcesDrive
{
param(
[Parameter(Mandatory, Position = 0)]
[System.Management.Automation.Runspaces.PSSession]$Session,
[switch]$SuppressErrors
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$labSourcesStorageAccount = Get-LabAzureLabSourcesStorage -ErrorAction SilentlyContinue
if ($Session.Runspace.ConnectionInfo.AuthenticationMechanism -notin 'CredSsp', 'Negotiate' -or -not $labSourcesStorageAccount)
{
return
}
$result = Invoke-Command -Session $Session -ScriptBlock {
#Add *.windows.net to Local Intranet Zone
$path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\windows.net'
if (-not (Test-Path -Path $path)) {
New-Item -Path $path -Force
New-ItemProperty $path -Name http -Value 1 -Type DWORD
New-ItemProperty $path -Name file -Value 1 -Type DWORD
}
$hostName = ([uri]$args[0]).Host
$dnsRecord = Resolve-DnsName -Name $hostname | Where-Object { $_ -is [Microsoft.DnsClient.Commands.DnsRecord_A] }
$ipAddress = $dnsRecord.IPAddress
$rangeName = $ipAddress.Replace('.', '')
$path = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Ranges\$rangeName"
if (-not (Test-Path -Path $path)) {
New-Item -Path $path -Force
New-ItemProperty $path -Name :Range -Value $ipAddress -Type String
New-ItemProperty $path -Name http -Value 1 -Type DWORD
New-ItemProperty $path -Name file -Value 1 -Type DWORD
}
$pattern = '^(OK|Unavailable) +(?<DriveLetter>\w): +\\\\automatedlab'
#remove all drive connected to an Azure LabSources share that are no longer available
$drives = net.exe use
$netRemoveResult = @()
foreach ($line in $drives)
{
if ($line -match $pattern)
{
$netRemoveResult += net.exe use "$($Matches.DriveLetter):" /d
}
}
$cmd = 'net.exe use * {0} /u:{1} {2}' -f $args[0], $args[1], $args[2]
$cmd = [scriptblock]::Create($cmd)
$netConnectResult = &$cmd 2>&1
if (-not $LASTEXITCODE)
{
$ALLabSourcesMapped = $true
$alDriveLetter = (Get-PSDrive | Where-Object DisplayRoot -like \\automatedlabsources*).Name
Get-ChildItem -Path "$($alDriveLetter):" | Out-Null #required, otherwise sometimes accessing the UNC path did not work
}
New-Object PSObject -Property @{
ReturnCode = $LASTEXITCODE
ALLabSourcesMapped = [bool](-not $LASTEXITCODE)
NetConnectResult = $netConnectResult
NetRemoveResult = $netRemoveResult
}
} -ArgumentList $labSourcesStorageAccount.Path, $labSourcesStorageAccount.StorageAccountName, $labSourcesStorageAccount.StorageAccountKey
$Session | Add-Member -Name ALLabSourcesMappingResult -Value $result -MemberType NoteProperty -Force
$Session | Add-Member -Name ALLabSourcesMapped -Value $result.ALLabSourcesMapped -MemberType NoteProperty -Force
if ($result.ReturnCode -ne 0 -and -not $SuppressErrors)
{
$netResult = $result | Where-Object { $_.ReturnCode -gt 0 }
Write-LogFunctionExitWithError -Message "Connecting session '$($s.Name)' to LabSources folder failed" -Details $netResult.NetConnectResult
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Connect-LWAzureLabSourcesDrive.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 920 |
```powershell
function Get-LWAzureVm
{
[CmdletBinding()]
param (
[Parameter()]
[string[]]$ComputerName
)
Test-LabHostConnected -Throw -Quiet
#required to suporess verbose messages, warnings and errors
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$azureVms = Get-AzVM -Status -ResourceGroupName (Get-LabAzureDefaultResourceGroup).ResourceGroupName -ErrorAction SilentlyContinue -ErrorVariable getazvmerror
$count = 1
while (-not $azureVms -and $count -le $azureRetryCount)
{
Write-ScreenInfo -Type Verbose -Message "Get-AzVM did not return anything, attempt $count of $($azureRetryCount) attempts. Azure presented us with the error: $($getazvmerror.Exception.Message)"
Start-Sleep -Seconds 2
$azureVms = Get-AzVM -Status -ResourceGroupName (Get-LabAzureDefaultResourceGroup).ResourceGroupName -ErrorAction SilentlyContinue -ErrorVariable getazvmerror
$count++
}
if (-not $azureVms)
{
Write-ScreenInfo -Message "Get-AzVM did not return anything in $($azureRetryCount) attempts, stopping lab deployment. Azure presented us with the error: $($getazvmerror.Exception.Message)"
throw "Get-AzVM did not return anything in $($azureRetryCount) attempts, stopping lab deployment. Azure presented us with the error: $($getazvmerror.Exception.Message)"
}
if ($ComputerName.Count -eq 0) { return $azureVms }
$azureVms | Where-Object Name -in $ComputerName
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Get-LWAzureVm.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 401 |
```powershell
function Enable-LWAzureVMRemoting
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification = "Not enabling CredSSP a third time on Linux")]
param
(
[Parameter(Mandatory, Position = 0)]
[string[]]$ComputerName,
[switch]$UseSSL
)
Test-LabHostConnected -Throw -Quiet
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
if ($ComputerName)
{
$machines = Get-LabVM -All -IncludeLinux | Where-Object Name -in $ComputerName
}
else
{
$machines = Get-LabVM -All -IncludeLinux
}
$script = {
param ($DomainName, $UserName, $Password)
$RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
Set-ItemProperty -Path $RegPath -Name AutoAdminLogon -Value 1 -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultUserName -Value $UserName -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultPassword -Value $Password -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultDomainName -Value $DomainName -ErrorAction SilentlyContinue
#Enable-WSManCredSSP works fine when called remotely on 2012 servers but not on 2008 (Access Denied). In case Enable-WSManCredSSP fails
#the settings are done in the registry directly
try
{
Enable-WSManCredSSP -Role Server -Force | Out-Null
}
catch
{
New-ItemProperty -Path HKLM:\software\Microsoft\Windows\CurrentVersion\WSMAN\Service -Name auth_credssp -Value 1 -PropertyType DWORD -Force
New-ItemProperty -Path HKLM:\software\Microsoft\Windows\CurrentVersion\WSMAN\Service -Name allow_remote_requests -Value 1 -PropertyType DWORD -Force
}
}
foreach ($machine in $machines)
{
$cred = $machine.GetCredential((Get-Lab))
try
{
Invoke-LabCommand -ComputerName $machine -ActivityName SetLabVMRemoting -ScriptBlock $script -DoNotUseCredSsp -NoDisplay `
-ArgumentList $machine.DomainName, $cred.UserName, $cred.GetNetworkCredential().Password -ErrorAction Stop -UseLocalCredential
}
catch
{
if ($IsLinux)
{
return
}
if ($UseSSL)
{
Connect-WSMan -ComputerName $machine.AzureConnectionInfo.DnsName -Credential $cred -Port $machine.AzureConnectionInfo.Port -UseSSL -SessionOption (New-WSManSessionOption -SkipCACheck -SkipCNCheck)
}
else
{
Connect-WSMan -ComputerName $machine.AzureConnectionInfo.DnsName -Credential $cred -Port $machine.AzureConnectionInfo.Port
}
Set-Item -Path "WSMan:\$($machine.AzureConnectionInfo.DnsName)\Service\Auth\CredSSP" -Value $true
Disconnect-WSMan -ComputerName $machine.AzureConnectionInfo.DnsName
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Enable-LWAzureVMRemoting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 732 |
```powershell
function Dismount-LWAzureIsoImage
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification = "Not relevant, used in Invoke-LabCommand")]
param
(
[Parameter(Mandatory, Position = 0)]
[string[]]
$ComputerName
)
Test-LabHostConnected -Throw -Quiet
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
Invoke-LabCommand -ComputerName $ComputerName -ActivityName "Dismounting ISO Images on Azure machines $($ComputerName -join ',')" -ScriptBlock {
Get-Volume |
Where-Object DriveType -eq CD-ROM |
ForEach-Object {
Get-DiskImage -DevicePath $_.Path.TrimEnd('\') -ErrorAction SilentlyContinue
} |
ForEach-Object {
Write-Verbose -Message "Dismounting '$($_.ImagePath)'"
$_ | Dismount-DiskImage
}
Get-ChildItem -Path C:\ALMounts\*.iso -ErrorAction SilentlyContinue | Remove-Item
} -NoDisplay
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Dismount-LWAzureIsoImage.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 249 |
```powershell
function Restore-LWAzureVmSnapshot
{
[Cmdletbinding()]
Param
(
[Parameter(Mandatory)]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[string]$SnapshotName
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$lab = Get-Lab
$resourceGroupName = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
$runningMachines = Get-LabVM -IsRunning -ComputerName $ComputerName -IncludeLinux
if ($runningMachines)
{
Stop-LWAzureVM -ComputerName $runningMachines -StayProvisioned $true
Wait-LabVMShutdown -ComputerName $runningMachines
}
$vms = Get-AzVM -ResourceGroupName $resourceGroupName | Where-Object Name -In $ComputerName
$machineStatus = @{}
$ComputerName.ForEach( { $machineStatus[$_] = @{ Stage1 = $null; Stage2 = $null; Stage3 = $null } })
foreach ($machine in $ComputerName)
{
$vm = $vms | Where-Object Name -eq $machine
$vmSnapshotName = '{0}_{1}' -f $machine, $SnapshotName
if (-not $vm)
{
Write-ScreenInfo -Message "$machine could not be found in $($resourceGroupName). Skipping snapshot." -type Warning
continue
}
$snapshot = Get-AzSnapshot -SnapshotName $vmSnapshotName -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
if (-not $snapshot)
{
Write-ScreenInfo -Message "No snapshot named $vmSnapshotName found for $machine. Skipping restore." -Type Warning
continue
}
$osDiskName = $vm.StorageProfile.OsDisk.name
$oldOsDisk = Get-AzDisk -Name $osDiskName -ResourceGroupName $resourceGroupName
$disksToRemove += $oldOsDisk.Name
$storageType = $oldOsDisk.sku.name
$diskconf = New-AzDiskConfig -AccountType $storagetype -Location $oldOsdisk.Location -SourceResourceId $snapshot.Id -CreateOption Copy
$machineStatus[$machine].Stage1 = @{
VM = $vm
OldDisk = $oldOsDisk.Name
Job = New-AzDisk -Disk $diskconf -ResourceGroupName $resourceGroupName -DiskName "$($vm.Name)-$((New-Guid).ToString())" -AsJob
}
}
if ($machineStatus.Values.Stage1.Job)
{
$null = $machineStatus.Values.Stage1.Job | Wait-Job
}
$failedStage1 = $($machineStatus.GetEnumerator() | Where-Object -FilterScript { $_.Value.Stage1.Job.State -eq 'Failed' }).Name
if ($failedStage1) { Write-ScreenInfo -Type Error -Message "The following machines failed to create a new disk from the snapshot: $($failedStage1 -join ',')" }
$ComputerName = $($machineStatus.GetEnumerator() | Where-Object -FilterScript { $_.Value.Stage1.Job.State -eq 'Completed' }).Name
foreach ($machine in $ComputerName)
{
$vm = $vms | Where-Object Name -eq $machine
$newDisk = $machineStatus[$machine].Stage1.Job | Receive-Job -Keep
$null = Set-AzVMOSDisk -VM $vm -ManagedDiskId $newDisk.Id -Name $newDisk.Name
$machineStatus[$machine].Stage2 = @{
Job = Update-AzVM -ResourceGroupName $resourceGroupName -VM $vm -AsJob
}
}
if ($machineStatus.Values.Stage2.Job)
{
$null = $machineStatus.Values.Stage2.Job | Wait-Job
}
$failedStage2 = $($machineStatus.GetEnumerator() | Where-Object -FilterScript { $_.Value.Stage2.Job.State -eq 'Failed' }).Name
if ($failedStage2) { Write-ScreenInfo -Type Error -Message "The following machines failed to update with the new OS disk created from a snapshot: $($failedStage2 -join ',')" }
$ComputerName = $($machineStatus.GetEnumerator() | Where-Object -FilterScript { $_.Value.Stage2.Job.State -eq 'Completed' }).Name
foreach ($machine in $ComputerName)
{
$disk = $machineStatus[$machine].Stage1.OldDisk
$machineStatus[$machine].Stage3 = @{
Job = Remove-AzDisk -ResourceGroupName $resourceGroupName -DiskName $disk -Confirm:$false -Force -AsJob
}
}
if ($machineStatus.Values.Stage3.Job)
{
$null = $machineStatus.Values.Stage3.Job | Wait-Job
}
$failedStage3 = $($machineStatus.GetEnumerator() | Where-Object -FilterScript { $_.Value.Stage3.Job.State -eq 'Failed' }).Name
if ($failedStage3)
{
$failedDisks = $failedStage3.ForEach( { $machineStatus[$_].Stage1.OldDisk })
Write-ScreenInfo -Type Warning -Message "The following machines failed to remove their old OS disk in a background job: $($failedStage3 -join ','). Trying to remove the disks again synchronously."
foreach ($machine in $failedStage3)
{
$disk = $machineStatus[$machine].Stage1.OldDisk
$null = Remove-AzDisk -ResourceGroupName $resourceGroupName -DiskName $disk -Confirm:$false -Force
}
}
if ($runningMachines)
{
Start-LWAzureVM -ComputerName $runningMachines
Wait-LabVM -ComputerName $runningMachines
}
if ($machineStatus.Values.Values.Job)
{
$machineStatus.Values.Values.Job | Remove-Job
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Restore-LWAzureVmSnapshot.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,283 |
```powershell
function Get-LWAzureVmSnapshot
{
param
(
[Parameter()]
[Alias('VMName')]
[string[]]
$ComputerName,
[Parameter()]
[Alias('Name')]
[string]
$SnapshotName
)
Test-LabHostConnected -Throw -Quiet
$snapshots = Get-AzSnapshot -ResourceGroupName (Get-LabAzureDefaultResourceGroup).Name -ErrorAction SilentlyContinue
if ($SnapshotName)
{
$snapshots = $snapshots | Where-Object { ($_.Name -split '_')[1] -eq $SnapshotName }
}
if ($ComputerName)
{
$snapshots = $snapshots | Where-Object { ($_.Name -split '_')[0] -in $ComputerName }
}
$snapshots.ForEach({
[AutomatedLab.Snapshot]::new(($_.Name -split '_')[1], ($_.Name -split '_')[0], $_.TimeCreated)
})
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Get-LWAzureVmSnapshot.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 216 |
```powershell
function Enable-LWAzureAutoShutdown
{
param
(
[string[]]
$ComputerName,
[timespan]
$Time,
[string]
$TimeZone = (Get-TimeZone).Id,
[switch]
$Wait
)
$lab = Get-Lab -ErrorAction Stop
$labVms = Get-AzVm -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
if ($ComputerName)
{
$labVms = $labVms | Where-Object Name -in $ComputerName
}
$resourceIdString = '{0}/providers/microsoft.devtestlab/schedules/shutdown-computevm-' -f $lab.AzureSettings.DefaultResourceGroup.ResourceId
$jobs = foreach ($vm in $labVms)
{
$properties = @{
status = 'Enabled'
taskType = 'ComputeVmShutdownTask'
dailyRecurrence = @{time = $Time.ToString('hhmm') }
timeZoneId = $TimeZone
targetResourceId = $vm.Id
}
New-AzResource -ResourceId ("$($resourceIdString)$($vm.Name)") -Location $vm.Location -Properties $properties -Force -ErrorAction SilentlyContinue -AsJob
}
if ($jobs -and $Wait.IsPresent)
{
$null = $jobs | Wait-Job
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Enable-LWAzureAutoShutdown.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 302 |
```powershell
function Get-LWAzureVMConnectionInfo
{
param (
[Parameter(Mandatory)]
[AutomatedLab.Machine[]]$ComputerName
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$lab = Get-Lab -ErrorAction SilentlyContinue
$retryCount = 5
if (-not $lab)
{
Write-PSFMessage "Could not retrieve machine info for '$($ComputerName.Name -join ',')'. No lab was imported."
}
if (-not ((Get-AzContext).Subscription.Name -eq $lab.AzureSettings.DefaultSubscription))
{
Set-AzContext -Subscription $lab.AzureSettings.DefaultSubscription
}
$resourceGroupName = (Get-LabAzureDefaultResourceGroup).ResourceGroupName
$azureVMs = Get-AzVM -ResourceGroupName $resourceGroupName | Where-Object Name -in $ComputerName.ResourceName
$ips = Get-AzPublicIpAddress -ResourceGroupName $resourceGroupName -ErrorAction SilentlyContinue
foreach ($name in $ComputerName)
{
$azureVM = $azureVMs | Where-Object Name -eq $name.ResourceName
if (-not $azureVM)
{ continue }
$net = $lab.VirtualNetworks.Where({ $_.Name -eq $name.Network[0] })
$ip = $ips | Where-Object { $_.Tag['Vnet'] -eq $net.ResourceName }
if (-not $ip)
{
$ip = $ips | Where-Object Name -eq "$($resourceGroupName)$($net.ResourceName)lbfrontendip"
}
if (-not $ip)
{
Write-ScreenInfo -Type Error -Message "No public IP address found for VM $($name.ResourceName) with tag $($net.ResourceName) or name $($resourceGroupName)$($net.ResourceName)lbfrontendip"
continue
}
$result = [AutomatedLab.Azure.AzureConnectionInfo] @{
ComputerName = $name.Name
DnsName = $ip.DnsSettings.Fqdn
HttpsName = $ip.DnsSettings.Fqdn
VIP = $ip.IpAddress
Port = $name.LoadBalancerWinrmHttpPort
HttpsPort = $name.LoadBalancerWinrmHttpsPort
RdpPort = $name.LoadBalancerRdpPort
SshPort = $name.LoadBalancerSshPort
ResourceGroupName = $azureVM.ResourceGroupName
}
Write-PSFMessage "Get-LWAzureVMConnectionInfo created connection info for VM '$name'"
Write-PSFMessage "ComputerName = $($name.Name)"
Write-PSFMessage "DnsName = $($ip.DnsSettings.Fqdn)"
Write-PSFMessage "HttpsName = $($ip.DnsSettings.Fqdn)"
Write-PSFMessage "VIP = $($ip.IpAddress)"
Write-PSFMessage "Port = $($name.LoadBalancerWinrmHttpPort)"
Write-PSFMessage "HttpsPort = $($name.LoadBalancerWinrmHttpsPort)"
Write-PSFMessage "RdpPort = $($name.LoadBalancerRdpPort)"
Write-PSFMessage "SshPort = $($name.LoadBalancerSshPort)"
Write-PSFMessage "ResourceGroupName = $($azureVM.ResourceGroupName)"
$result
}
Write-LogFunctionExit -ReturnValue $result
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Get-LWAzureVMConnectionInfo.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 764 |
```powershell
function Wait-LWAzureRestartVM
{
param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[switch]$DoNotUseCredSsp,
[double]$TimeoutInMinutes = 15,
[int]$ProgressIndicator,
[switch]$NoNewLine,
[Parameter(Mandatory)]
[datetime]
$MonitoringStartTime
)
Test-LabHostConnected -Throw -Quiet
#required to suporess verbose messages, warnings and errors
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$start = $MonitoringStartTime.ToUniversalTime()
Write-PSFMessage -Message "Starting monitoring the servers at '$start'"
$machines = Get-LabVM -ComputerName $ComputerName
$cmd = {
param (
[datetime]$Start
)
$Start = $Start.ToLocalTime()
(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootupTime -ge $Start
}
$ProgressIndicatorTimer = (Get-Date)
do
{
$machines = foreach ($machine in $machines)
{
if (((Get-Date) - $ProgressIndicatorTimer).TotalSeconds -ge $ProgressIndicator)
{
Write-ProgressIndicator
$ProgressIndicatorTimer = (Get-Date)
}
$hasRestarted = Invoke-LabCommand -ComputerName $machine -ActivityName WaitForRestartEvent -ScriptBlock $cmd -ArgumentList $start.Ticks -UseLocalCredential -DoNotUseCredSsp:$DoNotUseCredSsp -PassThru -Verbose:$false -NoDisplay -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if (-not $hasRestarted)
{
$events = Invoke-LabCommand -ComputerName $machine -ActivityName WaitForRestartEvent -ScriptBlock $cmd -ArgumentList $start.Ticks -DoNotUseCredSsp:$DoNotUseCredSsp -PassThru -Verbose:$false -NoDisplay -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
}
if ($hasRestarted)
{
Write-PSFMessage -Message "VM '$machine' has been restarted"
}
else
{
Start-Sleep -Seconds 10
$machine
}
}
}
until ($machines.Count -eq 0 -or (Get-Date).ToUniversalTime().AddMinutes( - $TimeoutInMinutes) -gt $start)
if (-not $NoNewLine)
{
Write-ProgressIndicatorEnd
}
if ((Get-Date).ToUniversalTime().AddMinutes( - $TimeoutInMinutes) -gt $start)
{
foreach ($machine in ($machines))
{
Write-Error -Message "Timeout while waiting for computers to restart. Computers '$machine' not restarted" -TargetObject $machine
}
}
Write-PSFMessage -Message "Finished monitoring the servers at '$(Get-Date)'"
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Wait-LWAzureRestartVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 687 |
```powershell
function Get-LWAzureSku
{
[Cmdletbinding()]
param
(
[Parameter(Mandatory)]
[AutomatedLab.Machine]$Machine
)
$lab = Get-Lab
#if this machine has a SQL Server role
foreach ($role in $Machine.Roles)
{
if ($role.Name -match 'SQLServer(?<SqlVersion>\d{4})')
{
#get the SQL Server version defined in the role
$sqlServerRoleName = $Matches[0]
$sqlServerVersion = $Matches.SqlVersion
if ($role.Properties.Keys | Where-Object { $_ -ne 'InstallSampleDatabase' })
{
$useStandardVm = $true
}
}
if ($role.Name -match 'VisualStudio(?<Version>\d{4})')
{
$visualStudioRoleName = $Matches[0]
$visualStudioVersion = $Matches.Version
}
}
if ($sqlServerRoleName -and -not $useStandardVm)
{
Write-PSFMessage -Message 'This is going to be a SQL Server VM'
$pattern = 'SQL(?<SqlVersion>\d{4})(?<SqlIsR2>R2)??(?<SqlServicePack>SP\d)?-(?<OS>WS\d{4}(R2)?)'
#get all SQL images matching the RegEx pattern and then get only the latest one
$sqlServerImages = $lab.AzureSettings.VmImages | Where-Object Offer -notlike "*BYOL*"
if ([System.Convert]::ToBoolean($Machine.AzureProperties['UseByolImage']))
{
$sqlServerImages = $lab.AzureSettings.VmImages | Where-Object Offer -like '*-BYOL'
}
$sqlServerImages = $sqlServerImages |
Where-Object Offer -Match $pattern |
Group-Object -Property Sku, Offer |
ForEach-Object {
$_.Group | Sort-Object -Property PublishedDate -Descending | Select-Object -First 1
}
#add the version, SP Level and OS from the ImageFamily field to the image object
foreach ($sqlServerImage in $sqlServerImages)
{
$sqlServerImage.Offer -match $pattern | Out-Null
$sqlServerImage | Add-Member -Name SqlVersion -Value $Matches.SqlVersion -MemberType NoteProperty -Force
$sqlServerImage | Add-Member -Name SqlIsR2 -Value $Matches.SqlIsR2 -MemberType NoteProperty -Force
$sqlServerImage | Add-Member -Name SqlServicePack -Value $Matches.SqlServicePack -MemberType NoteProperty -Force
$sqlServerImage | Add-Member -Name OS -Value (New-Object AutomatedLab.OperatingSystem($Matches.OS)) -MemberType NoteProperty -Force
}
#get the image that matches the OS and SQL server version
$machineOs = New-Object AutomatedLab.OperatingSystem($machine.OperatingSystem)
$vmImage = $sqlServerImages | Where-Object { $_.SqlVersion -eq $sqlServerVersion -and $_.OS.Version -eq $machineOs.Version } |
Sort-Object -Property SqlServicePack -Descending | Select-Object -First 1
$offerName = $vmImageName = $vmImage.Offer
$publisherName = $vmImage.PublisherName
$skusName = $vmImage.Skus
if (-not $vmImageName)
{
Write-ScreenInfo 'SQL Server image could not be found. The following combinations are currently supported by Azure:' -Type Warning
foreach ($sqlServerImage in $sqlServerImages)
{
Write-PSFMessage -Level Host $sqlServerImage.Offer
}
throw "There is no Azure VM image for '$sqlServerRoleName' on operating system '$($machine.OperatingSystem)'. The machine cannot be created. Cancelling lab setup. Please find the available images above."
}
}
elseif ($visualStudioRoleName)
{
Write-PSFMessage -Message 'This is going to be a Visual Studio VM'
$pattern = 'VS-(?<Version>\d{4})-(?<Edition>\w+)-VSU(?<Update>\d)-AzureSDK-\d{2,3}-((?<OS>WIN\d{2})|(?<OS>WS\d{4,6}))'
#get all SQL images machting the RegEx pattern and then get only the latest one
$visualStudioImages = $lab.AzureSettings.VmImages |
Where-Object Offer -EQ VisualStudio
#add the version, SP Level and OS from the ImageFamily field to the image object
foreach ($visualStudioImage in $visualStudioImages)
{
$visualStudioImage.Skus -match $pattern | Out-Null
$visualStudioImage | Add-Member -Name Version -Value $Matches.Version -MemberType NoteProperty -Force
$visualStudioImage | Add-Member -Name Update -Value $Matches.Update -MemberType NoteProperty -Force
$visualStudioImage | Add-Member -Name OS -Value (New-Object AutomatedLab.OperatingSystem($Matches.OS)) -MemberType NoteProperty -Force
}
#get the image that matches the OS and SQL server version
$machineOs = New-Object AutomatedLab.OperatingSystem($machine.OperatingSystem)
$vmImage = $visualStudioImages | Where-Object { $_.Version -eq $visualStudioVersion -and $_.OS.Version.Major -eq $machineOs.Version.Major } |
Sort-Object -Property Update -Descending | Select-Object -First 1
$offerName = $vmImageName = ($vmImage).Offer
$publisherName = ($vmImage).PublisherName
$skusName = ($vmImage).Skus
if (-not $vmImageName)
{
Write-ScreenInfo 'Visual Studio image could not be found. The following combinations are currently supported by Azure:' -Type Warning
foreach ($visualStudioImage in $visualStudioImages)
{
Write-ScreenInfo ('{0} - {1} - {2}' -f $visualStudioImage.Offer, $visualStudioImage.Skus, $visualStudioImage.Id)
}
throw "There is no Azure VM image for '$visualStudioRoleName' on operating system '$($machine.OperatingSystem)'. The machine cannot be created. Cancelling lab setup. Please find the available images above."
}
}
else
{
$vmImage = $lab.AzureSettings.VmImages |
Where-Object { $_.AutomatedLabOperatingSystemName -eq $Machine.OperatingSystem.OperatingSystemName -and $_.HyperVGeneration -eq "V$($Machine.VmGeneration)" } |
Select-Object -First 1
if (-not $vmImage)
{
throw "There is no Azure VM image for the operating system '$($Machine.OperatingSystem)'. The machine cannot be created. Cancelling lab setup."
}
$offerName = ($vmImage).Offer
$publisherName = ($vmImage).PublisherName
$skusName = ($vmImage).Skus
$version = $vmImage.Version
}
Write-PSFMessage -Message "We selected the SKUs $skusName from offer $offerName by publisher $publisherName"
@{
offer = $offerName
publisher = $publisherName
sku = $skusName
version = if ($version) { $version } else { 'latest' }
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Get-LWAzureSku.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,655 |
```powershell
function New-LabAzureResourceGroupDeployment
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[AutomatedLab.Lab]
$Lab,
[Parameter()]
[switch]
$PassThru,
[Parameter()]
[switch]
$Wait
)
Write-LogFunctionEntry
$template = @{
'$schema' = "path_to_url#"
contentVersion = '1.0.0.0'
parameters = @{ }
resources = @()
}
# The handy providers() function was deprecated and the latest provider APIs started getting error-prone and unpredictable
# The following list was generated on Jul 12 2022
$apiVersions = if (Get-LabConfigurationItem -Name UseLatestAzureProviderApi)
{
$providers = Get-AzResourceProvider -Location $lab.AzureSettings.DefaultLocation.Location -ErrorAction SilentlyContinue | Where-Object RegistrationState -eq 'Registered'
$provHash = @{
NicApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Network').ResourceTypes | Where-Object ResourceTypeName -eq 'networkInterfaces').ApiVersions[0] # 2022-01-01
DiskApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Compute').ResourceTypes | Where-Object ResourceTypeName -eq 'disks').ApiVersions[0] # 2022-01-01
LoadBalancerApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Network').ResourceTypes | Where-Object ResourceTypeName -eq 'loadBalancers').ApiVersions[0] # 2022-01-01
PublicIpApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Network').ResourceTypes | Where-Object ResourceTypeName -eq 'publicIpAddresses').ApiVersions[0] # 2022-01-01
VirtualNetworkApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Network').ResourceTypes | Where-Object ResourceTypeName -eq 'virtualNetworks').ApiVersions[0] # 2022-01-01
NsgApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Network').ResourceTypes | Where-Object ResourceTypeName -eq 'networkSecurityGroups').ApiVersions[0] # 2022-01-01
VmApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Compute').ResourceTypes | Where-Object ResourceTypeName -eq 'virtualMachines').ApiVersions[1] # 2022-03-01
}
if (-not $lab.AzureSettings.IsAzureStack)
{
$provHash.BastionHostApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Network').ResourceTypes | Where-Object ResourceTypeName -eq 'bastionHosts').ApiVersions[0] # 2022-01-01
}
if ($lab.AzureSettings.IsAzureStack)
{
$provHash.VmApi = (($providers | Where-Object ProviderNamespace -eq 'Microsoft.Compute').ResourceTypes | Where-Object ResourceTypeName -eq 'virtualMachines').ApiVersions[0]
}
$provHash
}
elseif ($Lab.AzureSettings.IsAzureStack)
{
@{
NicApi = '2018-11-01'
DiskApi = '2018-11-01'
LoadBalancerApi = '2018-11-01'
PublicIpApi = '2018-11-01'
VirtualNetworkApi = '2018-11-01'
NsgApi = '2018-11-01'
VmApi = '2020-06-01'
}
}
else
{
@{
NicApi = '2022-01-01'
DiskApi = '2022-01-01'
LoadBalancerApi = '2022-01-01'
PublicIpApi = '2022-01-01'
VirtualNetworkApi = '2022-01-01'
BastionHostApi = '2022-01-01'
NsgApi = '2022-01-01'
VmApi = '2022-03-01'
}
}
#region Network Security Group
Write-ScreenInfo -Type Verbose -Message 'Adding network security group to template, enabling traffic to ports 3389,5985,5986,22 for VMs behind load balancer'
[string[]]$allowedIps = (Get-LabVm -IncludeLinux).AzureProperties["LoadBalancerAllowedIp"] | Foreach-Object { $_ -split '\s*[,;]\s*' } | Where-Object { -not [string]::IsNullOrWhitespace($_) }
$nsg = @{
type = "Microsoft.Network/networkSecurityGroups"
apiVersion = $apiVersions['NsgApi']
name = "nsg"
location = "[resourceGroup().location]"
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
}
properties = @{
securityRules = @(
# Necessary mgmt ports for AutomatedLab
@{
name = "NecessaryPorts"
properties = @{
protocol = "TCP"
sourcePortRange = "*"
sourceAddressPrefix = if ($allowedIps) { $null } else { "*" }
destinationAddressPrefix = "VirtualNetwork"
access = "Allow"
priority = 100
direction = "Inbound"
sourcePortRanges = @()
destinationPortRanges = @(
"22"
"3389"
"5985"
"5986"
)
sourceAddressPrefixes = @()
destinationAddressPrefixes = @()
}
}
# Rules for bastion host deployment - always included to be able to deploy bastion at a later stage
@{
name = "BastionIn"
properties = @{
protocol = "TCP"
sourcePortRange = "*"
sourceAddressPrefix = if ($allowedIps) { $null } else { "*" }
destinationAddressPrefix = "*"
access = "Allow"
priority = 101
direction = "Inbound"
sourcePortRanges = @()
destinationPortRanges = @(
"443"
)
sourceAddressPrefixes = @()
destinationAddressPrefixes = @()
}
}
if (-not $Lab.AzureSettings.IsAzureStack)
{
@{
name = "BastionMgmtOut"
properties = @{
protocol = "TCP"
sourcePortRange = "*"
sourceAddressPrefix = "*"
destinationAddressPrefix = "AzureCloud"
access = "Allow"
priority = 100
direction = "Outbound"
sourcePortRanges = @()
destinationPortRanges = @(
"443"
)
sourceAddressPrefixes = @()
destinationAddressPrefixes = @()
}
}
@{
name = "BastionRdsOut"
properties = @{
protocol = "TCP"
sourcePortRange = "*"
sourceAddressPrefix = "*"
destinationAddressPrefix = "VirtualNetwork"
access = "Allow"
priority = 101
direction = "Outbound"
sourcePortRanges = @()
destinationPortRanges = @(
"3389"
"22"
)
sourceAddressPrefixes = @()
destinationAddressPrefixes = @()
}
}
}
)
}
}
if ($allowedIps)
{
$nsg.properties.securityrules | Where-Object { $_.properties.direction -eq 'Inbound' } | Foreach-object { $_.properties.sourceAddressPrefixes = $allowedIps }
}
$template.resources += $nsg
#endregion
#region Wait for availability of Bastion
if ($Lab.AzureSettings.AllowBastionHost -and -not $lab.AzureSettings.IsAzureStack)
{
$bastionFeature = Get-AzProviderFeature -FeatureName AllowBastionHost -ProviderNamespace Microsoft.Network
while (($bastionFeature).RegistrationState -ne 'Registered')
{
if ($bastionFeature.RegistrationState -eq 'NotRegistered')
{
$null = Register-AzProviderFeature -FeatureName AllowBastionHost -ProviderNamespace Microsoft.Network
$null = Register-AzProviderFeature -FeatureName bastionShareableLink -ProviderNamespace Microsoft.Network
}
Start-Sleep -Seconds 5
Write-ScreenInfo -Type Verbose -Message "Waiting for registration of bastion host feature. Current status: $(($bastionFeature).RegistrationState)"
$bastionFeature = Get-AzProviderFeature -FeatureName AllowBastionHost -ProviderNamespace Microsoft.Network
}
}
$vnetCount = 0
$loadbalancers = @{}
foreach ($network in $Lab.VirtualNetworks)
{
#region VNet
Write-ScreenInfo -Type Verbose -Message ('Adding vnet {0} ({1}) to template' -f $network.ResourceName, $network.AddressSpace)
$vNet = @{
type = "Microsoft.Network/virtualNetworks"
apiVersion = $apiVersions['VirtualNetworkApi']
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
}
dependsOn = @(
"[resourceId('Microsoft.Network/networkSecurityGroups', 'nsg')]"
)
name = $network.ResourceName
location = "[resourceGroup().location]"
properties = @{
addressSpace = @{
addressPrefixes = @(
$network.AddressSpace.ToString()
)
}
subnets = @()
dhcpOptions = @{
dnsServers = @()
}
}
}
if (-not $network.Subnets)
{
Write-ScreenInfo -Type Verbose -Message ('Adding default subnet ({0}) to VNet' -f $network.AddressSpace)
$vnet.properties.subnets += @{
name = "default"
properties = @{
addressPrefix = $network.AddressSpace.ToString()
networkSecurityGroup = @{
id = "[resourceId('Microsoft.Network/networkSecurityGroups', 'nsg')]"
}
}
}
}
foreach ($subnet in $network.Subnets)
{
Write-ScreenInfo -Type Verbose -Message ('Adding subnet {0} ({1}) to VNet' -f $subnet.Name, $subnet.AddressSpace)
$vnet.properties.subnets += @{
name = $subnet.Name
properties = @{
addressPrefix = $subnet.AddressSpace.ToString()
networkSecurityGroup = @{
id = "[resourceId('Microsoft.Network/networkSecurityGroups', 'nsg')]"
}
}
}
}
if ($Lab.AzureSettings.AllowBastionHost -and -not $lab.AzureSettings.IsAzureStack)
{
if ($network.Subnets.Name -notcontains 'AzureBastionSubnet')
{
$sourceMask = $network.AddressSpace.Cidr
$sourceMaskIp = $network.AddressSpace.NetMask
$sourceRange = Get-NetworkRange -IPAddress $network.AddressSpace.IpAddress.AddressAsString -SubnetMask $network.AddressSpace.NetMask
$sourceInfo = Get-NetworkSummary -IPAddress $network.AddressSpace.IpAddress.AddressAsString -SubnetMask $network.AddressSpace.NetMask
$superNetMask = $sourceMask - 1
$superNetIp = $network.AddressSpace.IpAddress.AddressAsString
$superNet = [AutomatedLab.VirtualNetwork]::new()
$superNet.AddressSpace = '{0}/{1}' -f $superNetIp, $superNetMask
$superNetInfo = Get-NetworkSummary -IPAddress $superNet.AddressSpace.IpAddress.AddressAsString -SubnetMask $superNet.AddressSpace.NetMask
foreach ($address in (Get-NetworkRange -IPAddress $superNet.AddressSpace.IpAddress.AddressAsString -SubnetMask $superNet.AddressSpace.NetMask))
{
if ($address -in @($sourceRange + $sourceInfo.Network + $sourceInfo.Broadcast))
{
continue
}
$bastionNet = [AutomatedLab.VirtualNetwork]::new()
$bastionNet.AddressSpace = '{0}/{1}' -f $address, $sourceMask
break
}
$vNet.properties.addressSpace.addressPrefixes = @(
$superNet.AddressSpace.ToString()
)
$vnet.properties.subnets += @{
name = 'AzureBastionSubnet'
properties = @{
addressPrefix = $bastionNet.AddressSpace.ToString()
networkSecurityGroup = @{
id = "[resourceId('Microsoft.Network/networkSecurityGroups', 'nsg')]"
}
}
}
}
$dnsLabel = "[concat('azbastion', uniqueString(resourceGroup().id))]"
Write-ScreenInfo -Type Verbose -Message ('Adding Azure bastion public static IP with DNS label {0} to template' -f $dnsLabel)
$template.resources +=
@{
apiVersion = $apiVersions['PublicIpApi']
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
}
type = "Microsoft.Network/publicIPAddresses"
name = "$($vnetCount)bip"
location = "[resourceGroup().location]"
properties = @{
publicIPAllocationMethod = "static"
dnsSettings = @{
domainNameLabel = $dnsLabel
}
}
sku = @{
name = if ($Lab.AzureSettings.IsAzureStack) { 'Basic' } else { 'Standard' }
}
}
$template.resources += @{
apiVersion = $apiVersions['BastionHostApi']
type = "Microsoft.Network/bastionHosts"
name = "bastion$vnetCount"
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
}
location = "[resourceGroup().location]"
dependsOn = @(
"[resourceId('Microsoft.Network/virtualNetworks', '$($network.ResourceName)')]"
"[resourceId('Microsoft.Network/publicIPAddresses', '$($vnetCount)bip')]"
)
properties = @{
ipConfigurations = @(
@{
name = "IpConf"
properties = @{
subnet = @{
id = "[resourceId('Microsoft.Network/virtualNetworks/subnets', '$($network.ResourceName)','AzureBastionSubnet')]"
}
publicIPAddress = @{
id = "[resourceId('Microsoft.Network/publicIPAddresses', '$($vnetCount)bip')]"
}
}
}
)
}
}
}
$template.resources += $vNet
#endregion
#region Peering
foreach ($peer in $network.ConnectToVnets)
{
Write-ScreenInfo -Type Verbose -Message ('Adding peering from {0} to {1} to VNet template' -f $network.ResourceName, $peer)
$template.Resources += @{
apiVersion = $apiVersions['VirtualNetworkApi']
dependsOn = @(
"[resourceId('Microsoft.Network/virtualNetworks', '$($network.ResourceName)')]"
"[resourceId('Microsoft.Network/virtualNetworks', '$($peer)')]"
)
type = "Microsoft.Network/virtualNetworks/virtualNetworkPeerings"
name = "$($network.ResourceName)/$($network.ResourceName)To$($peer)"
properties = @{
allowVirtualNetworkAccess = $true
allowForwardedTraffic = $false
allowGatewayTransit = $false
useRemoteGateways = $false
remoteVirtualNetwork = @{
id = "[resourceId('Microsoft.Network/virtualNetworks', '$peer')]"
}
}
}
$template.Resources += @{
apiVersion = $apiVersions['VirtualNetworkApi']
dependsOn = @(
"[resourceId('Microsoft.Network/virtualNetworks', '$($network.ResourceName)')]"
"[resourceId('Microsoft.Network/virtualNetworks', '$($peer)')]"
)
type = "Microsoft.Network/virtualNetworks/virtualNetworkPeerings"
name = "$($peer)/$($peer)To$($network.ResourceName)"
properties = @{
allowVirtualNetworkAccess = $true
allowForwardedTraffic = $false
allowGatewayTransit = $false
useRemoteGateways = $false
remoteVirtualNetwork = @{
id = "[resourceId('Microsoft.Network/virtualNetworks', '$($network.ResourceName)')]"
}
}
}
}
foreach ($externalPeer in $network.PeeringVnetResourceIds) {
$peerName = $externalPeer -split '/' | Select-Object -Last 1
Write-ScreenInfo -Type Verbose -Message ('Adding peering from {0} to {1} to VNet template' -f $network.ResourceName, $peerName)
$template.Resources += @{
apiVersion = $apiVersions['VirtualNetworkApi']
dependsOn = @(
"[resourceId('Microsoft.Network/virtualNetworks', '$($network.ResourceName)')]"
)
type = "Microsoft.Network/virtualNetworks/virtualNetworkPeerings"
name = "$($network.ResourceName)/$($network.ResourceName)To$($peerName)"
properties = @{
allowVirtualNetworkAccess = $true
allowForwardedTraffic = $false
allowGatewayTransit = $false
useRemoteGateways = $false
remoteVirtualNetwork = @{
id = $externalPeer
}
}
}
}
#endregion
#region Public Ip
$dnsLabel = "[concat('al$vnetCount-', uniqueString(resourceGroup().id))]"
if ($network.AzureDnsLabel)
{
$dnsLabel = $network.AzureDnsLabel
}
Write-ScreenInfo -Type Verbose -Message ('Adding public static IP with DNS label {0} to template' -f $dnsLabel)
$template.resources +=
@{
apiVersion = $apiVersions['PublicIpApi']
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
Vnet = $network.ResourceName
}
type = "Microsoft.Network/publicIPAddresses"
name = "lbip$vnetCount"
location = "[resourceGroup().location]"
properties = @{
publicIPAllocationMethod = "static"
dnsSettings = @{
domainNameLabel = $dnsLabel
}
}
sku = @{
name = if ($Lab.AzureSettings.IsAzureStack) { 'Basic' } else { 'Standard' }
}
}
#endregion
#region Load balancer
Write-ScreenInfo -Type Verbose -Message ('Adding load balancer to template')
$loadbalancers[$network.ResourceName] = @{
Name = "lb$vnetCount"
Backend = "$($vnetCount)lbbc"
}
$loadBalancer = @{
type = "Microsoft.Network/loadBalancers"
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
Vnet = $network.ResourceName
}
apiVersion = $apiVersions['LoadBalancerApi']
name = "lb$vnetCount"
location = "[resourceGroup().location]"
sku = @{
name = if ($Lab.AzureSettings.IsAzureStack) { 'Basic' } else { 'Standard' }
}
dependsOn = @(
"[resourceId('Microsoft.Network/publicIPAddresses', 'lbip$vnetCount')]"
)
properties = @{
frontendIPConfigurations = @(
@{
name = "$($vnetCount)lbfc"
properties = @{
publicIPAddress = @{
id = "[resourceId('Microsoft.Network/publicIPAddresses', 'lbip$vnetCount')]"
}
}
}
)
backendAddressPools = @(
@{
name = "$($vnetCount)lbbc"
}
)
}
}
if (-not $Lab.AzureSettings.IsAzureStack)
{
$loadbalancer.properties.outboundRules = @(
@{
name = "InternetAccess"
properties = @{
allocatedOutboundPorts = 0 # In order to use automatic allocation
frontendIPConfigurations = @(
@{
id = "[resourceId('Microsoft.Network/loadBalancers/frontendIPConfigurations', 'lb$vnetCount', '$($vnetCount)lbfc')]"
}
)
backendAddressPool = @{
id = "[concat(resourceId('Microsoft.Network/loadBalancers', 'lb$vnetCount'), '/backendAddressPools/$($vnetCount)lbbc')]"
}
protocol = "All"
enableTcpReset = $true
idleTimeoutInMinutes = 4
}
}
)
}
$rules = foreach ($machine in ($Lab.Machines | Where-Object -FilterScript { $_.Network -EQ $network.Name -and -not $_.SkipDeployment }))
{
Write-ScreenInfo -Type Verbose -Message ('Adding inbound NAT rules for {0}: {1}:3389, {2}:5985, {3}:5986, {4}:22' -f $machine, $machine.LoadBalancerRdpPort, $machine.LoadBalancerWinRmHttpPort, $machine.LoadBalancerWinrmHttpsPort, $machine.LoadBalancerSshPort)
@{
name = "$($machine.ResourceName.ToLower())rdpin"
properties = @{
frontendIPConfiguration = @{
id = "[resourceId('Microsoft.Network/loadBalancers/frontendIPConfigurations', 'lb$vnetCount', '$($vnetCount)lbfc')]"
}
frontendPort = $machine.LoadBalancerRdpPort
backendPort = 3389
enableFloatingIP = $false
protocol = "Tcp"
}
}
@{
name = "$($machine.ResourceName.ToLower())winrmin"
properties = @{
frontendIPConfiguration = @{
id = "[resourceId('Microsoft.Network/loadBalancers/frontendIPConfigurations', 'lb$vnetCount', '$($vnetCount)lbfc')]"
}
frontendPort = $machine.LoadBalancerWinRmHttpPort
backendPort = 5985
enableFloatingIP = $false
protocol = "Tcp"
}
}
@{
name = "$($machine.ResourceName.ToLower())winrmhttpsin"
properties = @{
frontendIPConfiguration = @{
id = "[resourceId('Microsoft.Network/loadBalancers/frontendIPConfigurations', 'lb$vnetCount', '$($vnetCount)lbfc')]"
}
frontendPort = $machine.LoadBalancerWinrmHttpsPort
backendPort = 5986
enableFloatingIP = $false
protocol = "Tcp"
}
}
@{
name = "$($machine.ResourceName.ToLower())sshin"
properties = @{
frontendIPConfiguration = @{
id = "[resourceId('Microsoft.Network/loadBalancers/frontendIPConfigurations', 'lb$vnetCount', '$($vnetCount)lbfc')]"
}
frontendPort = $machine.LoadBalancerSshPort
backendPort = 22
enableFloatingIP = $false
protocol = "Tcp"
}
}
}
$loadBalancer.properties.inboundNatRules = $rules
$template.resources += $loadBalancer
#endregion
$vnetCount++
}
#region Disks
foreach ($disk in $Lab.Disks)
{
if (-not $disk) { continue } # Due to an issue with the disk collection being enumerated even if it is empty
Write-ScreenInfo -Type Verbose -Message ('Creating managed data disk {0} ({1} GB)' -f $disk.Name, $disk.DiskSize)
$vm = $lab.Machines | Where-Object { $_.Disks.Name -contains $disk.Name }
$template.resources += @{
type = "Microsoft.Compute/disks"
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
}
apiVersion = $apiVersions['DiskApi']
name = $disk.Name
location = "[resourceGroup().location]"
sku = @{
name = if ($vm.AzureProperties.StorageSku)
{
$vm.AzureProperties['StorageSku']
}
else
{
"Standard_LRS"
}
}
properties = @{
creationData = @{
createOption = "Empty"
}
diskSizeGB = $disk.DiskSize
}
}
}
#endregion
foreach ($machine in $Lab.Machines.Where({ -not $_.SkipDeployment }))
{
$niccount = 0
foreach ($nic in $machine.NetworkAdapters)
{
Write-ScreenInfo -Type Verbose -Message ('Creating NIC {0}' -f $nic.InterfaceName)
$subnetName = 'default'
foreach ($subnetConfig in $nic.VirtualSwitch.Subnets)
{
if ($subnetConfig.Name -eq 'AzureBastionSubnet') { continue }
$usable = Get-NetworkRange -IPAddress $subnetConfig.AddressSpace.IpAddress.AddressAsString -SubnetMask $subnetConfig.AddressSpace.Cidr
if ($nic.Ipv4Address[0].IpAddress.AddressAsString -in $usable)
{
$subnetName = $subnetConfig.Name
}
}
$machineInboundRules = @(
@{
id = "[concat(resourceId('Microsoft.Network/loadBalancers', '$($loadBalancers[$nic.VirtualSwitch.ResourceName].Name)'),'/inboundNatRules/$($machine.ResourceName.ToLower())rdpin')]"
}
@{
id = "[concat(resourceId('Microsoft.Network/loadBalancers', '$($loadBalancers[$nic.VirtualSwitch.ResourceName].Name)'),'/inboundNatRules/$($machine.ResourceName.ToLower())winrmin')]"
}
@{
id = "[concat(resourceId('Microsoft.Network/loadBalancers', '$($loadBalancers[$nic.VirtualSwitch.ResourceName].Name)'),'/inboundNatRules/$($machine.ResourceName.ToLower())winrmhttpsin')]"
}
@{
id = "[concat(resourceId('Microsoft.Network/loadBalancers', '$($loadBalancers[$nic.VirtualSwitch.ResourceName].Name)'),'/inboundNatRules/$($machine.ResourceName.ToLower())sshin')]"
}
)
$nicTemplate = @{
dependsOn = @(
"[resourceId('Microsoft.Network/virtualNetworks', '$($nic.VirtualSwitch.ResourceName)')]"
"[resourceId('Microsoft.Network/loadBalancers', '$($loadBalancers[$nic.VirtualSwitch.ResourceName].Name)')]"
)
properties = @{
enableAcceleratedNetworking = $false
ipConfigurations = @(
@{
properties = @{
subnet = @{
id = "[resourceId('Microsoft.Network/virtualNetworks/subnets', '$($nic.VirtualSwitch.ResourceName)', '$subnetName')]"
}
primary = $true
privateIPAllocationMethod = "Static"
privateIPAddress = $nic.Ipv4Address[0].IpAddress.AddressAsString
privateIPAddressVersion = "IPv4"
}
name = "ipconfig1"
}
)
enableIPForwarding = $false
}
name = "$($machine.ResourceName)nic$($niccount)"
apiVersion = $apiVersions['NicApi']
type = "Microsoft.Network/networkInterfaces"
location = "[resourceGroup().location]"
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
}
}
# Add NAT only to first nic
if ($niccount -eq 0)
{
$nicTemplate.properties.ipConfigurations[0].properties.loadBalancerInboundNatRules = $machineInboundRules
$nicTemplate.properties.ipConfigurations[0].properties.loadBalancerBackendAddressPools = @(
@{
id = "[concat(resourceId('Microsoft.Network/loadBalancers', '$($loadBalancers[$nic.VirtualSwitch.ResourceName].Name)'), '/backendAddressPools/$($loadBalancers[$nic.VirtualSwitch.ResourceName].Backend)')]"
}
)
}
if (($Lab.VirtualNetworks | Where-Object ResourceName -eq $nic.VirtualSwitch).DnsServers)
{
$nicTemplate.properties.dnsSettings = @{
dnsServers = [string[]](($Lab.VirtualNetworks | Where-Object ResourceName -eq $nic.VirtualSwitch).DnsServers.AddressAsString)
}
}
if ($nic.Ipv4DnsServers)
{
$nicTemplate.properties.dnsSettings = @{
dnsServers = [string[]]($nic.Ipv4DnsServers.AddressAsString)
}
}
$template.resources += $nicTemplate
$niccount++
}
Write-ScreenInfo -Type Verbose -Message ('Adding machine template')
$vmSize = Get-LWAzureVmSize -Machine $Machine
$imageRef = Get-LWAzureSku -Machine $machine
if (-not $vmSize)
{
throw "No valid VM size found for '$Machine'. For a list of available role sizes, use the command 'Get-LabAzureAvailableRoleSize -LocationName $($lab.AzureSettings.DefaultLocation.Location)'"
}
Write-ScreenInfo -Type Verbose -Message "Adding $Machine with size $vmSize, publisher $($imageRef.publisher), offer $($imageRef.offer), sku $($imageRef.sku)!"
$machTemplate = @{
name = $machine.ResourceName
tags = @{
AutomatedLab = $Lab.Name
CreationTime = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
}
dependsOn = @()
properties = @{
storageProfile = @{
osDisk = @{
createOption = "FromImage"
osType = $Machine.OperatingSystemType.ToString()
caching = "ReadWrite"
managedDisk = @{
storageAccountType = if ($Machine.AzureProperties.ContainsKey('StorageSku') -and $Machine.AzureProperties['StorageSku'] -notmatch 'ultra')
{
$Machine.AzureProperties['StorageSku']
}
elseif ($Machine.AzureProperties.ContainsKey('StorageSku') -and $Machine.AzureProperties['StorageSku'] -match 'ultra')
{
Write-ScreenInfo -Type Warning -Message "Ultra_SSD SKU selected, defaulting to Premium_LRS for OS disk."
'Premium_LRS'
}
else
{
'Standard_LRS'
}
}
}
imageReference = $imageRef
dataDisks = @()
}
networkProfile = @{
networkInterfaces = @()
}
osProfile = @{
adminPassword = $machine.GetLocalCredential($true).GetNetworkCredential().Password
computerName = $machine.Name
allowExtensionOperations = $true
adminUsername = if ($machine.OperatingSystemType -eq 'Linux') { 'automatedlab' } else { ($machine.GetLocalCredential($true).UserName -split '\\')[-1] }
}
hardwareProfile = @{
vmSize = $vmSize.Name
}
}
type = "Microsoft.Compute/virtualMachines"
apiVersion = $apiVersions['VmApi']
location = "[resourceGroup().location]"
}
if ($machine.OperatingSystem.OperatingSystemName -like 'Kali*')
{
# This is a marketplace offer, so we have to do redundant stuff for no good reason
$machTemplate.plan = @{
name = $imageRef.sku # Otherwise known as sku
product = $imageRef.offer # Otherwise known as offer
publisher = $imageRef.publisher # publisher
}
}
if ($machine.OperatingSystemType -eq 'Windows')
{
$machTemplate.properties.osProfile.windowsConfiguration = @{
enableAutomaticUpdates = $true
provisionVMAgent = $true
winRM = @{
listeners = @(
@{
protocol = "Http"
}
)
}
}
}
if ($machine.OperatingSystemType -eq 'Linux')
{
if ($machine.SshPublicKey)
{
$machTemplate.properties.osProfile.linuxConfiguration = @{
disablePasswordAuthentication = $true
enableVMAgentPlatformUpdates = $true
provisionVMAgent = $true
ssh = @{
publicKeys = [hashtable[]]@(@{
keyData = $machine.SshPublicKey
path = "/home/automatedlab/.ssh/authorized_keys"
}
)
}
}
}
}
if ($machine.AzureProperties['EnableSecureBoot'] -and -not $lab.AzureSettings.IsAzureStack) # Available only in public regions
{
$machTemplate.properties.securityProfile = @{
securityType = 'TrustedLaunch'
uefiSettings = @{
secureBootEnabled = $true
vTpmEnabled = $Machine.AzureProperties['EnableTpm'] -match '1|true|yes'
}
}
}
$luncount = 0
foreach ($disk in $machine.Disks)
{
if (-not $disk) { continue } # Due to an issue with the disk collection being enumerated even if it is empty
Write-ScreenInfo -Type Verbose -Message ('Adding disk {0} to machine template' -f $disk.Name)
$machTemplate.properties.storageProfile.dataDisks += @{
lun = $luncount
name = $disk.Name
createOption = "attach"
managedDisk = @{
id = "[resourceId('Microsoft.Compute/disks/', '$($disk.Name)')]"
}
}
$luncount++
}
$niccount = 0
foreach ($nic in $machine.NetworkAdapters)
{
Write-ScreenInfo -Type Verbose -Message ('Adding NIC {0} to template' -f $nic.InterfaceName)
$machtemplate.dependsOn += "[resourceId('Microsoft.Network/networkInterfaces', '$($machine.ResourceName)nic$($niccount)')]"
$machTemplate.properties.networkProfile.networkInterfaces += @{
id = "[resourceId('Microsoft.Network/networkInterfaces', '$($machine.ResourceName)nic$($niccount)')]"
properties = @{
primary = $niccount -eq 0
}
}
$niccount++
}
$template.resources += $machTemplate
}
$rgDeplParam = @{
TemplateObject = $template
ResourceGroupName = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
Force = $true
}
$templatePath = Join-Path -Path (Get-LabConfigurationItem -Name LabAppDataRoot) -ChildPath "Labs/$($Lab.Name)/armtemplate.json"
$template | ConvertTo-JsonNewtonsoft | Set-Content -Path $templatePath
Write-ScreenInfo -Message "Deploying new resource group with template $templatePath"
# Without wait - unable to catch exception
if ($Wait.IsPresent)
{
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$count = 1
while ($count -le $azureRetryCount -and -not $deployment)
{
try
{
$deployment = New-AzResourceGroupDeployment @rgDeplParam -ErrorAction Stop
}
catch
{
if ($_.Exception.Message -match 'Code:NoRegisteredProviderFound')
{
$count++
}
else
{
Write-Error -Message 'Unrecoverable error during resource group deployment' -Exception $_.Exception
return
}
}
}
if ($count -gt $azureRetryCount)
{
Write-Error -Message 'Unrecoverable error during resource group deployment'
return
}
}
else
{
$deployment = New-AzResourceGroupDeployment @rgDeplParam -AsJob # Splatting AsJob did not work
}
if ($PassThru.IsPresent)
{
$deployment
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/New-LabAzureResourceGroupDeployment.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 8,055 |
```powershell
function Get-LWAzureAutoShutdown
{
[CmdletBinding()]
param ( )
$lab = Get-Lab -ErrorAction Stop
$resourceGroup = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
$schedules = (Get-AzResource -ResourceGroupName $resourceGroup -ResourceType Microsoft.DevTestLab/schedules -ExpandProperties -ErrorAction SilentlyContinue).Properties
foreach ($schedule in $schedules)
{
$hour, $minute = Get-StringSection -SectionSize 2 -String $schedule.dailyRecurrence.time
if ($schedule)
{
[PSCustomObject]@{
ComputerName = ($schedule.targetResourceId -split '/')[-1]
Time = New-TimeSpan -Hours $hour -Minutes $minute
TimeZone = Get-TimeZone -Id $schedule.timeZoneId
}
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Get-LWAzureAutoShutdown.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 188 |
```powershell
function Checkpoint-LWAzureVM
{
[Cmdletbinding()]
Param
(
[Parameter(Mandatory)]
[string[]]$ComputerName,
[Parameter(Mandatory)]
[string]$SnapshotName
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$lab = Get-Lab
$resourceGroupName = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
$runningMachines = Get-LabVM -IsRunning -ComputerName $ComputerName -IncludeLinux
if ($runningMachines)
{
Stop-LWAzureVM -ComputerName $runningMachines -StayProvisioned $true
Wait-LabVMShutdown -ComputerName $runningMachines
}
$jobs = foreach ($machine in $ComputerName)
{
$vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $machine -ErrorAction SilentlyContinue
if (-not $vm)
{
Write-ScreenInfo -Message "$machine could not be found in $($resourceGroupName). Skipping snapshot." -type Warning
continue
}
$vmSnapshotName = '{0}_{1}' -f $machine, $SnapshotName
$existingSnapshot = Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $vmSnapshotName -ErrorAction SilentlyContinue
if ($existingSnapshot)
{
Write-ScreenInfo -Message "Snapshot $SnapshotName for $machine already exists as $($existingSnapshot.Name). Not creating it again." -Type Warning
continue
}
$osSourceDisk = Get-AzDisk -ResourceGroupName $resourceGroupName -DiskName $vm.StorageProfile.OsDisk.Name
$snapshotConfig = New-AzSnapshotConfig -SourceUri $osSourceDisk.Id -CreateOption Copy -Location $vm.Location
New-AzSnapshot -Snapshot $snapshotConfig -SnapshotName $vmSnapshotName -ResourceGroupName $resourceGroupName -AsJob
}
if ($jobs.State -contains 'Failed')
{
Write-ScreenInfo -Type Error -Message "At least one snapshot creation failed: $($jobs.Name -join ',')."
$skipRemove = $true
}
if ($jobs)
{
$null = $jobs | Wait-Job
$jobs | Remove-Job
}
if ($runningMachines)
{
Start-LWAzureVM -ComputerName $runningMachines
Wait-LabVM -ComputerName $runningMachines
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Checkpoint-LWAzureVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 539 |
```powershell
function Stop-LWAzureVM
{
param (
[Parameter(Mandatory)]
[string[]]
$ComputerName,
[ValidateRange(0, 300)]
[int]$ProgressIndicator = (Get-LabConfigurationItem -Name DefaultProgressIndicator),
[switch]
$NoNewLine,
[switch]
$ShutdownFromOperatingSystem,
[bool]
$StayProvisioned = $false
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
if (-not $PSBoundParameters.ContainsKey('ProgressIndicator')) { $PSBoundParameters.Add('ProgressIndicator', $ProgressIndicator) } #enables progress indicator
$lab = Get-Lab
$machines = Get-LabVm -ComputerName $ComputerName -IncludeLinux
$azureVms = Get-AzVM -ResourceGroupName (Get-LabAzureDefaultResourceGroup).ResourceGroupName
$azureVms = $azureVms | Where-Object { $_.Name -in $machines.ResourceName }
if ($ShutdownFromOperatingSystem)
{
$jobs = @()
$linux, $windows = $machines.Where( { $_.OperatingSystemType -eq 'Linux' }, 'Split')
$jobs += Invoke-LabCommand -ComputerName $windows -NoDisplay -AsJob -PassThru -ScriptBlock {
Stop-Computer -Force -ErrorAction Stop
}
$jobs += Invoke-LabCommand -UseLocalCredential -ComputerName $linux -NoDisplay -AsJob -PassThru -ScriptBlock {
#Sleep as background process so that job does not fail.
[void] (Start-Job {
Start-Sleep -Seconds 5
shutdown -P now
})
}
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator $ProgressIndicator
$failedJobs = $jobs | Where-Object { $_.State -eq 'Failed' }
if ($failedJobs)
{
Write-ScreenInfo -Message "Could not stop Azure VM(s): '$($failedJobs.Location)'" -Type Error
}
}
else
{
$jobs = foreach ($name in $machines.ResourceName)
{
$vm = $azureVms | Where-Object Name -eq $name
$vm | Stop-AzVM -Force -StayProvisioned:$StayProvisioned -AsJob
}
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator $ProgressIndicator
$failedJobs = $jobs | Where-Object { $_.State -eq 'Failed' }
if ($failedJobs)
{
$jobNames = ($failedJobs | ForEach-Object {
if ($_.Name.StartsWith("StopAzureVm_"))
{
($_.Name -split "_")[1]
}
elseif ($_.Name -match "Long Running Operation for 'Stop-AzVM' on resource '(?<MachineName>[\w-]+)'")
{
$Matches.MachineName
}
}) -join ", "
Write-ScreenInfo -Message "Could not stop Azure VM(s): '$jobNames'" -Type Error
}
}
Write-ProgressIndicatorEnd
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Stop-LWAzureVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 719 |
```powershell
function Remove-LWAzureVM
{
Param (
[Parameter(Mandatory)]
[string]$Name,
[switch]$AsJob,
[switch]$PassThru
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$Lab = Get-Lab
$vm = Get-AzVM -ResourceGroupName $Lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -Name $Name -ErrorAction SilentlyContinue
$null = $vm | Remove-AzVM -Force
foreach ($loadBalancer in (Get-AzLoadBalancer -ResourceGroupName $Lab.AzureSettings.DefaultResourceGroup.ResourceGroupName))
{
$rules = $loadBalancer | Get-AzLoadBalancerInboundNatRuleConfig | Where-Object Name -like "$($Name)*"
foreach ($rule in $rules)
{
$null = Remove-AzLoadBalancerInboundNatRuleConfig -LoadBalancer $loadBalancer -Name $rule.Name -Confirm:$false
}
}
$vmResources = Get-AzResource -ResourceGroupName $Lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -Name "$($name)*"
$jobs = $vmResources | Remove-AzResource -AsJob -Force -Confirm:$false
if (-not $AsJob.IsPresent)
{
$null = $jobs | Wait-Job
}
if ($PassThru.IsPresent)
{
$jobs
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Remove-LWAzureVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 330 |
```powershell
function Initialize-LWAzureVM
{
[Cmdletbinding()]
Param (
[Parameter(Mandatory)]
[AutomatedLab.Machine[]]$Machine
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$lab = Get-Lab
$initScript = {
param(
[string]
$UserLocale,
[string]
$TimeZoneId,
[string]
$Disks,
[string]
$LabSourcesPath,
[string]
$StorageAccountName,
[string]
$StorageAccountKey,
[string[]]
$DnsServers,
[int]
$WinRmMaxEnvelopeSizeKb,
[int]
$WinRmMaxConcurrentOperationsPerUser,
[int]
$WinRmMaxConnections,
[string]
$PublicKey
)
$defaultSettings = @{
WinRmMaxEnvelopeSizeKb = 500
WinRmMaxConcurrentOperationsPerUser = 1500
WinRmMaxConnections = 300
}
$null = mkdir C:\DeployDebug -ErrorAction SilentlyContinue
$null = Start-Transcript -OutputDirectory C:\DeployDebug
Start-Service WinRm
foreach ($setting in $defaultSettings.GetEnumerator())
{
if ($PSBoundParameters[$setting.Key].Value -ne $setting.Value)
{
$subdir = if ($setting.Key -match 'MaxEnvelope') { $null } else { 'Service\' }
Set-Item "WSMAN:\localhost\$subdir$($setting.Key.Replace('WinRm',''))" $($PSBoundParameters[$setting.Key]) -Force
}
}
Enable-PSRemoting -Force -SkipNetworkProfileCheck
Enable-WSManCredSSP -Role Server -Force
#region Region Settings Xml
$regionSettings = @'
<gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend">
<!-- user list -->
<gs:UserList>
<gs:User UserID="Current" CopySettingsToDefaultUserAcct="true" CopySettingsToSystemAcct="true"/>
</gs:UserList>
<!-- GeoID -->
<gs:LocationPreferences>
<gs:GeoID Value="{1}"/>
</gs:LocationPreferences>
<!-- system locale -->
<gs:SystemLocale Name="{0}"/>
<!-- user locale -->
<gs:UserLocale>
<gs:Locale Name="{0}" SetAsCurrent="true" ResetAllSettings="true"/>
</gs:UserLocale>
</gs:GlobalizationServices>
'@
#endregion
try
{
$geoId = [System.Globalization.RegionInfo]::new($UserLocale).GeoId
}
catch
{
$geoId = 244 #default is US
}
if (-not (Test-Path 'C:\AL'))
{
$alDir = New-Item -ItemType Directory -Path C:\AL -Force
}
$alDir = 'C:\AL'
$tempFile = Join-Path -Path $alDir -ChildPath RegionalSettings
$regionSettings -f $UserLocale, $geoId | Out-File -FilePath $tempFile
$argument = 'intl.cpl,,/f:"{0}"' -f $tempFile
control.exe $argument
Start-Sleep -Seconds 1
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine -Force
$idx = (Get-NetIPInterface | Where-object { $_.AddressFamily -eq "IPv4" -and $_.InterfaceAlias -like "*Ethernet*" }).ifIndex
$dnsServer = Get-DnsClientServerAddress -InterfaceIndex $idx -AddressFamily IPv4
Set-DnsClientServerAddress -InterfaceIndex $idx -ServerAddresses 168.63.129.16
$release = Invoke-RestMethod -Uri 'path_to_url -UseBasicParsing -ErrorAction SilentlyContinue
$uri = ($release.assets | Where-Object name -like '*-win-x64.msi').browser_download_url
if (-not $uri)
{
$uri = 'path_to_url
}
Invoke-WebRequest -Uri $uri -UseBasicParsing -OutFile C:\PS7.msi -ErrorAction SilentlyContinue
Start-Process -Wait -FilePath msiexec '/package C:\PS7.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=0 ENABLE_PSREMOTING=0 REGISTER_MANIFEST=0 USE_MU=0 ENABLE_MU=0' -NoNewWindow -PassThru -ErrorAction SilentlyContinue
Remove-Item -Path C:\PS7.msi -ErrorAction SilentlyContinue
# Configure SSHD for PowerShell Remoting alternative that also works on Linux
if (Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*')
{
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 -ErrorAction SilentlyContinue
Start-Service sshd -ErrorAction SilentlyContinue
Set-Service -Name sshd -StartupType 'Automatic' -ErrorAction SilentlyContinue
if (-not (Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue))
{
New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 -Profile Any
}
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Program Files\powershell\7\pwsh.exe" -PropertyType String -Force -ErrorAction SilentlyContinue
$null = New-Item -Force -Path C:\AL\SSH -ItemType Directory
if ($PublicKey) { $PublicKey | Set-Content -Path (Join-Path -Path C:\AL\SSH -ChildPath 'keys') }
Start-Process -Wait -FilePath icacls.exe -ArgumentList "$(Join-Path -Path C:\AL\SSH -ChildPath 'keys') /inheritance:r /grant ""Administrators:F"" /grant ""SYSTEM:F""" -ErrorAction SilentlyContinue
$sshdConfig = @"
Port 22
PasswordAuthentication no
PubkeyAuthentication yes
GSSAPIAuthentication yes
AllowGroups Users Administrators
AuthorizedKeysFile c:/al/ssh/keys
Subsystem powershell c:/progra~1/powershell/7/pwsh.exe -sshs -NoLogo
"@
$sshdConfig | Set-Content -Path (Join-Path -Path $env:ProgramData -ChildPath 'ssh/sshd_config') -ErrorAction SilentlyContinue
Restart-Service -Name sshd -ErrorAction SilentlyContinue
}
Set-DnsClientServerAddress -InterfaceIndex $idx -ServerAddresses $dnsServer.ServerAddresses
#Set Power Scheme to High Performance
powercfg.exe -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
#Create a scheduled tasks that maps the Azure lab sources drive during each logon
if (-not [string]::IsNullOrWhiteSpace($LabSourcesPath))
{
$script = @'
$output = ''
$labSourcesPath = '{0}'
$pattern = '^(OK|Unavailable) +(?<DriveLetter>\w): +\\\\automatedlab'
#remove all drive connected to an Azure LabSources share that are no longer available
$drives = net.exe use
foreach ($line in $drives)
{{
if ($line -match $pattern)
{{
$output += net.exe use "$($Matches.DriveLetter):" /d
}}
}}
$output += cmdkey.exe /add:{1} /user:{2} /pass:{3}
Start-Sleep -Seconds 1
net.exe use * {0} /u:{2} {3}
$initialErrorCode = $LASTEXITCODE
if ($LASTEXITCODE -eq 2) {{
$hostName = ([uri]$labSourcesPath).Host
$dnsRecord = Resolve-DnsName -Name $hostname | Where-Object {{ $_ -is [Microsoft.DnsClient.Commands.DnsRecord_A] }}
$ipAddress = $dnsRecord.IPAddress
$alternativeLabSourcesPath = $labSourcesPath.Replace($hostName, $ipAddress)
$output += net.exe use * $alternativeLabSourcesPath /u:{2} {3}
}}
$finalErrorCode = $LASTEXITCODE
[pscustomobject]@{{
Output = $output
InitialErrorCode = $initialErrorCode
FinalErrorCode = $finalErrorCode
LabSourcesPath = $labSourcesPath
AlternativeLabSourcesPath = $alternativeLabSourcesPath
}}
'@
$cmdkeyTarget = ($LabSourcesPath -split '\\')[2]
$script = $script -f $LabSourcesPath, $cmdkeyTarget, $StorageAccountName, $StorageAccountKey
[pscustomobject]@{
Path = $LabSourcesPath
StorageAccountName = $StorageAccountName
StorageAccountKey = $StorageAccountKey
} | Export-Clixml -Path C:\AL\LabSourcesStorageAccount.xml
$script | Out-File C:\AL\AzureLabSources.ps1 -Force
}
#set the time zone
Set-TimeZone -Name $TimeZoneId
reg.exe add 'HKLM\SOFTWARE\Microsoft\ServerManager\oobe' /v DoNotOpenInitialConfigurationTasksAtLogon /d 1 /t REG_DWORD /f
reg.exe add 'HKLM\SOFTWARE\Microsoft\ServerManager' /v DoNotOpenServerManagerAtLogon /d 1 /t REG_DWORD /f
reg.exe add 'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' /v EnableFirstLogonAnimation /d 0 /t REG_DWORD /f
reg.exe add 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' /v FilterAdministratorToken /t REG_DWORD /d 0 /f
reg.exe add 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' /v EnableLUA /t REG_DWORD /d 0 /f
reg.exe add 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f
reg.exe add 'HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}' /v IsInstalled /t REG_DWORD /d 0 /f #disable admin IE Enhanced Security Configuration
reg.exe add 'HKLM\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}' /v IsInstalled /t REG_DWORD /d 0 /f #disable user IE Enhanced Security Configuration
reg.exe add 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' /v BgInfo /t REG_SZ /d "C:\AL\BgInfo.exe C:\AL\BgInfo.bgi /Timer:0 /nolicprompt" /f
#turn off the Windows firewall
Set-NetFirewallProfile -All -Enabled False -PolicyStore PersistentStore
if ($DnsServers.Count -gt 0)
{
Write-Verbose "Configuring $($DnsServers.Count) DNS Servers"
$idx = (Get-NetIPInterface | Where-object { $_.AddressFamily -eq "IPv4" -and $_.InterfaceAlias -like "*Ethernet*" }).ifIndex
Set-DnsClientServerAddress -InterfaceIndex $idx -ServerAddresses $DnsServers
}
#Add *.windows.net to Local Intranet Zone
$path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\windows.net'
New-Item -Path $path -Force
New-ItemProperty $path -Name http -Value 1 -Type DWORD
New-ItemProperty $path -Name file -Value 1 -Type DWORD
if (-not $Disks) { $null = try { Stop-Transcript -ErrorAction Stop } catch { }; return }
# Azure InvokeRunAsCommand is not very clever, so we sent the stuff as JSON
$Disks | Set-Content -Path C:\AL\disks.json
[object[]] $diskObjects = $Disks | ConvertFrom-Json
Write-Verbose -Message "Disk count for $env:COMPUTERNAME`: $($diskObjects.Count)"
foreach ($diskObject in $diskObjects.Where({ -not $_.SkipInitialization }))
{
$disk = Get-Disk | Where-Object Location -like "*LUN $($diskObject.LUN)"
$disk | Set-Disk -IsReadOnly $false
$disk | Set-Disk -IsOffline $false
$disk | Initialize-Disk -PartitionStyle GPT
$party = if ($diskObject.DriveLetter)
{
$disk | New-Partition -UseMaximumSize -DriveLetter $diskObject.DriveLetter
}
else
{
$disk | New-Partition -UseMaximumSize -AssignDriveLetter
}
$party | Format-Volume -Force -UseLargeFRS:$diskObject.UseLargeFRS -AllocationUnitSize $diskObject.AllocationUnitSize -NewFileSystemLabel $diskObject.Label
}
$null = try { Stop-Transcript -ErrorAction Stop } catch { }
}
$initScriptFile = New-Item -ItemType File -Path (Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath "$($Lab.Name)vminit.ps1") -Force
$initScript.ToString() | Set-Content -Path $initScriptFile -Force
# Configure AutoShutdown
if ($lab.AzureSettings.AutoShutdownTime)
{
$time = $lab.AzureSettings.AutoShutdownTime
$tz = if (-not $lab.AzureSettings.AutoShutdownTimeZone) { Get-TimeZone } else { Get-TimeZone -Id $lab.AzureSettings.AutoShutdownTimeZone }
Write-ScreenInfo -Message "Configuring auto-shutdown of all VMs daily at $($time) in timezone $($tz.Id)"
Enable-LWAzureAutoShutdown -ComputerName (Get-LabVm -IncludeLinux | Where-Object Name -notin $machineSpecific.Name) -Time $time -TimeZone $tz.Id -Wait
}
$machineSpecific = Get-LabVm -SkipConnectionInfo -IncludeLinux | Where-Object {
$_.AzureProperties.ContainsKey('AutoShutdownTime')
}
foreach ($machine in $machineSpecific)
{
$time = $machine.AzureProperties.AutoShutdownTime
$tz = if (-not $machine.AzureProperties.AutoShutdownTimezoneId) { Get-TimeZone } else { Get-TimeZone -Id $machine.AzureProperties.AutoShutdownTimezoneId }
Write-ScreenInfo -Message "Configure shutdown of $machine daily at $($time) in timezone $($tz.Id)"
Enable-LWAzureAutoShutdown -ComputerName $machine -Time $time -TimeZone $tz.Id -Wait
}
Write-ScreenInfo -Message 'Configuring localization and additional disks' -TaskStart -NoNewLine
if (-not $lab.AzureSettings.IsAzureStack) { $labsourcesStorage = Get-LabAzureLabSourcesStorage }
$jobs = [System.Collections.ArrayList]::new()
foreach ($m in ($Machine | Where-Object OperatingSystemType -eq 'Windows'))
{
[string[]]$DnsServers = ($m.NetworkAdapters | Where-Object { $_.VirtualSwitch.Name -eq $Lab.Name }).Ipv4DnsServers.AddressAsString
$azVmDisks = (Get-AzVm -Name $m.ResourceName -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName).StorageProfile.DataDisks
foreach ($machDisk in $m.Disks)
{
$machDisk.Lun = $azVmDisks.Where({ $_.Name -eq $machDisk.Name }).Lun
}
$diskJson = $m.disks | ConvertTo-Json -Compress
$scriptParam = @{
UserLocale = $m.UserLocale
TimeZoneId = $m.TimeZone
WinRmMaxEnvelopeSizeKb = Get-LabConfigurationItem -Name WinRmMaxEnvelopeSizeKb
WinRmMaxConcurrentOperationsPerUser = Get-LabConfigurationItem -Name WinRmMaxConcurrentOperationsPerUser
WinRmMaxConnections = Get-LabConfigurationItem -Name WinRmMaxConnections
}
$azsArgumentLine = '-UserLocale "{0}" -TimeZoneId "{1}" -WinRmMaxEnvelopeSizeKb {2} -WinRmMaxConcurrentOperationsPerUser {3} -WinRmMaxConnections {4}' -f $m.UserLocale, $m.TimeZone, (Get-LabConfigurationItem -Name WinRmMaxEnvelopeSizeKb), (Get-LabConfigurationItem -Name WinRmMaxConcurrentOperationsPerUser), (Get-LabConfigurationItem -Name WinRmMaxConnections)
if ($DnsServers.Count -gt 0)
{
$scriptParam.DnsServers = $DnsServers
$azsArgumentLine += ' -DnsServers "{0}"' -f ($DnsServers -join '","')
}
if ($m.SshPublicKey)
{
$scriptParam.PublicKey = $m.SshPublicKey
$azsArgumentLine += ' -PublicKey "{0}"' -f $m.SshPublicKey
}
if ($diskJson)
{
$scriptParam.Disks = $diskJson
$azsArgumentLine += " -Disks '{0}'" -f $diskJson
}
if ($labsourcesStorage)
{
$scriptParam.LabSourcesPath = $labsourcesStorage.Path
$scriptParam.StorageAccountName = $labsourcesStorage.StorageAccountName
$scriptParam.StorageAccountKey = $labsourcesStorage.StorageAccountKey
$azsArgumentLine += '-LabSourcesPath {0} -StorageAccountName {1} -StorageAccountKey {2}' -f $labsourcesStorage.Path, $labsourcesStorage.StorageAccountName, $labsourcesStorage.StorageAccountKey
}
if ($m.IsDomainJoined)
{
$domain = $lab.Domains | Where-Object Name -eq $m.DomainName
}
# Azure Stack - Create temporary storage account to upload script and use extension - sad, but true.
if ($Lab.AzureSettings.IsAzureStack)
{
$sa = Get-AzStorageAccount -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -ErrorAction SilentlyContinue
if (-not $sa)
{
$sa = New-AzStorageAccount -Name "cse$(-join (1..10 | % {[char](Get-Random -Min 97 -Max 122)}))" -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -SkuName Standard_LRS -Kind Storage -Location (Get-LabAzureDefaultLocation).Location
}
$co = $sa | Get-AzStorageContainer -Name customscriptextension -ErrorAction SilentlyContinue
if (-not $co)
{
$co = $sa | New-AzStorageContainer -Name customscriptextension
}
$content = Set-AzStorageBlobContent -File $initScriptFile -CloudBlobContainer $co.CloudBlobContainer -Blob $(Split-Path -Path $initScriptFile -Leaf) -Context $sa.Context -Force -ErrorAction Stop
$token = New-AzStorageBlobSASToken -CloudBlob $content.ICloudBlob -StartTime (Get-Date) -ExpiryTime $(Get-Date).AddHours(1) -Protocol HttpsOnly -Context $sa.Context -Permission r -ErrorAction Stop
$uri = '{0}{1}/{2}{3}' -f $co.Context.BlobEndpoint, 'customscriptextension', $(Split-Path -Path $initScriptFile -Leaf), $token
[version] $typehandler = (Get-AzVMExtensionImage -PublisherName Microsoft.Compute -Type CustomScriptExtension -Location (Get-LabAzureDefaultLocation).Location | Sort-Object { [version]$_.Version } | Select-Object -Last 1).Version
$extArg = @{
ResourceGroupName = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
VMName = $m.ResourceName
FileUri = $uri
TypeHandlerVersion = '{0}.{1}' -f $typehandler.Major, $typehandler.Minor
Name = 'initcustomizations'
Location = (Get-LabAzureDefaultLocation).Location
Run = Split-Path -Path $initScriptFile -Leaf
Argument = $azsArgumentLine
NoWait = $true
}
$Null = Set-AzVMCustomScriptExtension @extArg
}
else
{
$null = $jobs.Add((Invoke-AzVMRunCommand -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -VMName $m.ResourceName -ScriptPath $initScriptFile -Parameter $scriptParam -CommandId 'RunPowerShellScript' -ErrorAction Stop -AsJob))
}
}
$initScriptLinux = @'
sudo sed -i 's|[#]*GSSAPIAuthentication yes|GSSAPIAuthentication yes|g' /etc/ssh/sshd_config
sudo sed -i 's|[#]*PasswordAuthentication yes|PasswordAuthentication no|g' /etc/ssh/sshd_config
sudo sed -i 's|[#]*PubkeyAuthentication yes|PubkeyAuthentication yes|g' /etc/ssh/sshd_config
if [ -n "$(sudo cat /etc/ssh/sshd_config | grep 'Subsystem powershell')" ]; then
echo "PowerShell subsystem configured"
else
echo "Subsystem powershell /usr/bin/pwsh -sshs -NoLogo -NoProfile" | sudo tee --append /etc/ssh/sshd_config
fi
sudo mkdir -p /usr/local/share/powershell 2>/dev/null
sudo chmod 777 -R /usr/local/share/powershell
if [ -n "$(which apt 2>/dev/null)" ]; then
curl -sSL path_to_url | sudo apt-key add -
curl -sSL path_to_url | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc
sudo apt update
sudo apt install -y wget apt-transport-https software-properties-common
wget -q "path_to_url -rs)/packages-microsoft-prod.deb"
sudo dpkg -i packages-microsoft-prod.deb
sudo apt update
sudo apt install -y powershell
sudo apt install -y openssl omi omi-psrp-server
sudo apt install -y oddjob oddjob-mkhomedir sssd adcli krb5-workstation realmd samba-common samba-common-tools authselect-compat openssh-server
elif [ -n "$(which yum 2>/dev/null)" ]; then
sudo rpm -Uvh "path_to_url cat /etc/redhat-release | grep -oP "(\d)" | head -1)/packages-microsoft-prod.rpm"
sudo yum install -y powershell
sudo yum install -y openssl omi omi-psrp-server
sudo yum install -y oddjob oddjob-mkhomedir sssd adcli krb5-workstation realmd samba-common samba-common-tools authselect-compat openssh-server
elif [ -n "$(which dnf 2>/dev/null)" ]; then
sudo rpm -Uvh path_to_url cat /etc/redhat-release | grep -oP "(\d)" | head -1)/packages-microsoft-prod.rpm
sudo dnf install -y powershell
sudo dnf install -y openssl omi omi-psrp-server
sudo dnf install -y oddjob oddjob-mkhomedir sssd adcli krb5-workstation realmd samba-common samba-common-tools authselect-compat openssh-server
fi
sudo systemctl restart sshd
'@
$linuxInitFiles = foreach ($m in ($Machine | Where-Object OperatingSystemType -eq 'Linux'))
{
if ($Lab.AzureSettings.IsAzureStack)
{
Write-ScreenInfo -Type Warning -Message 'Linux VMs not yet implemented on Azure Stack, sorry.'
continue
}
$initScriptFileLinux = New-Item -ItemType File -Path (Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath "$($Lab.Name)$($m.Name)vminitlinux.bash") -Force
$initScriptLinux | Set-Content -Path $initScriptFileLinux -Force
$initScriptFileLinux
$null = $jobs.Add((Invoke-AzVMRunCommand -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -VMName $m.ResourceName -ScriptPath $initScriptFileLinux.FullName -CommandId 'RunShellScript' -ErrorAction Stop -AsJob))
}
if ($jobs)
{
Wait-LWLabJob -Job $jobs -ProgressIndicator 5 -Timeout 30 -NoDisplay
}
$initScriptFile | Remove-Item -ErrorAction SilentlyContinue
$linuxInitFiles | Copy-Item -Destination $Lab.LabPath
$linuxInitFiles | Remove-Item -ErrorAction SilentlyContinue
# And once again for all the VMs that for some unknown reason did not *really* execute the RunCommand
if (Get-Command ssh -ErrorAction SilentlyContinue)
{
Install-LabSshKnownHost
foreach ($m in ($Machine | Where-Object {$_.OperatingSystemType -eq 'Linux' -and $_.SshPrivateKeyPath}))
{
$ci = $m.AzureConnectionInfo
$null = ssh -p $ci.SshPort "automatedlab@$($ci.DnsName)" -i $m.SshPrivateKeyPath $initScriptLinux 2>$null
}
}
# Wait for VM extensions to be "done"
if ($lab.AzureSettings.IsAzureStack)
{
$extensionStatuus = Get-LabVm -IncludeLinux | Foreach-Object { Get-AzVMCustomScriptExtension -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -VMName $_.ResourceName -Name initcustomizations -ErrorAction SilentlyContinue }
$start = Get-Date
$timeout = New-TimeSpan -Minutes 5
while (($extensionStatuus.ProvisioningState -contains 'Updating' -or $extensionStatuus.ProvisioningState -contains 'Creating') -and ((Get-Date) - $start) -lt $timeout)
{
Start-Sleep -Seconds 5
$extensionStatuus = Get-LabVm -IncludeLinux | Foreach-Object { Get-AzVMCustomScriptExtension -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -VMName $_.ResourceName -Name initcustomizations -ErrorAction SilentlyContinue }
}
foreach ($network in $Lab.VirtualNetworks)
{
if ($network.DnsServers.Count -eq 0) { continue }
$vnet = Get-AzVirtualNetwork -Name $network.ResourceName -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
$vnet.dhcpOptions.dnsServers = [string[]]($network.DnsServers.AddressAsString)
$null = $vnet | Set-AzVirtualNetwork
}
}
Copy-LabFileItem -Path (Get-ChildItem -Path "$((Get-Module -Name AutomatedLabCore)[0].ModuleBase)\Tools\HyperV\*") -DestinationFolderPath /AL -ComputerName ($Machine | Where OperatingSystemType -eq 'Windows') -UseAzureLabSourcesOnAzureVm $false
$sessions = if ($PSVersionTable.PSVersion -ge [System.Version]'7.0')
{
New-LabPSSession $Machine
}
else
{
Write-ScreenInfo -Type Warning -Message "Skipping copy of AutomatedLab.Common to Linux VMs as Windows PowerShell is used on the host and not PowerShell 7+."
New-LabPSSession ($Machine | Where OperatingSystemType -eq 'Windows')
}
Send-ModuleToPSSession -Module (Get-Module -ListAvailable -Name AutomatedLab.Common | Select-Object -First 1) -Session $sessions -IncludeDependencies -Force
Write-ScreenInfo -Message 'Finished' -TaskEnd
Write-ScreenInfo -Message 'Stopping all new machines except domain controllers'
$machinesToStop = $Machine | Where-Object { $_.Roles.Name -notcontains 'RootDC' -and $_.Roles.Name -notcontains 'FirstChildDC' -and $_.Roles.Name -notcontains 'DC' -and $_.IsDomainJoined }
if ($machinesToStop)
{
Stop-LWAzureVM -ComputerName $machinesToStop -StayProvisioned $true
Wait-LabVMShutdown -ComputerName $machinesToStop
}
if ($machinesToStop)
{
Write-ScreenInfo -Message "$($Machine.Count) new Azure machines were configured. Some machines were stopped as they are not to be domain controllers '$($machinesToStop -join ', ')'"
}
else
{
Write-ScreenInfo -Message "($($Machine.Count)) new Azure machines were configured"
}
Write-PSFMessage "Removing all sessions after VmInit"
Remove-LabPSSession
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Initialize-LWAzureVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 6,545 |
```powershell
function Enable-LWAzureWinRm
{
param
(
[Parameter(Mandatory)]
[AutomatedLab.Machine[]]
$Machine,
[switch]
$PassThru,
[switch]
$Wait
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$lab = Get-Lab
$jobs = @()
$tempFileName = Join-Path -Path ([IO.Path]::GetTempPath()) -ChildPath enableazurewinrm.labtempfile.ps1
$customScriptContent = @'
$null = mkdir C:\DeployDebug -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Path C:\ALAzure -ErrorAction SilentlyContinue
'Trying to enable Remoting and CredSSP' | Out-File C:\ALAzure\WinRmActivation.log -Append
try
{
Enable-PSRemoting -Force -ErrorAction Stop
"Successfully called Enable-PSRemoting" | Out-File C:\ALAzure\WinRmActivation.log -Append
}
catch
{
"Error calling Enable-PSRemoting. $($_.Exception.Message)" | Out-File C:\ALAzure\WinRmActivation.log -Append
}
try
{
Enable-WSManCredSSP -Role Server -Force | Out-Null
"Successfully enabled CredSSP" | Out-File C:\ALAzure\WinRmActivation.log -Append
}
catch
{
try
{
New-ItemProperty -Path HKLM:\software\Microsoft\Windows\CurrentVersion\WSMAN\Service -Name auth_credssp -Value 1 -PropertyType DWORD -Force -ErrorACtion Stop
New-ItemProperty -Path HKLM:\software\Microsoft\Windows\CurrentVersion\WSMAN\Service -Name allow_remote_requests -Value 1 -PropertyType DWORD -Force -ErrorAction Stop
"Enabled CredSSP via Registry" | Out-File C:\ALAzure\WinRmActivation.log -Append
}
catch
{
"Could not enable CredSSP via cmdlet or registry!" | Out-File C:\ALAzure\WinRmActivation.log -Append
}
}
'@
$customScriptContent | Out-File $tempFileName -Force -Encoding utf8
$rgName = Get-LabAzureDefaultResourceGroup
$jobs = foreach ($m in $Machine)
{
if ($Lab.AzureSettings.IsAzureStack)
{
$sa = Get-AzStorageAccount -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -ErrorAction SilentlyContinue
if (-not $sa)
{
$sa = New-AzStorageAccount -Name "cse$(-join (1..10 | % {[char](Get-Random -Min 97 -Max 122)}))" -ResourceGroupName $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName -SkuName Standard_LRS -Kind Storage -Location (Get-LabAzureDefaultLocation).Location
}
$co = $sa | Get-AzStorageContainer -Name customscriptextension -ErrorAction SilentlyContinue
if (-not $co)
{
$co = $sa | New-AzStorageContainer -Name customscriptextension
}
$content = Set-AzStorageBlobContent -File $tempFileName -CloudBlobContainer $co.CloudBlobContainer -Blob $(Split-Path -Path $tempFileName -Leaf) -Context $sa.Context -Force -ErrorAction Stop
$token = New-AzStorageBlobSASToken -CloudBlob $content.ICloudBlob -StartTime (Get-Date) -ExpiryTime $(Get-Date).AddHours(1) -Protocol HttpsOnly -Context $sa.Context -Permission r -ErrorAction Stop
$uri = '{0}{1}/{2}{3}' -f $co.Context.BlobEndpoint, 'customscriptextension', $(Split-Path -Path $tempFileName -Leaf), $token
[version] $typehandler = (Get-AzVMExtensionImage -PublisherName Microsoft.Compute -Type CustomScriptExtension -Location (Get-LabAzureDefaultLocation).Location | Sort-Object { [version]$_.Version } | Select-Object -Last 1).Version
$extArg = @{
ResourceGroupName = $lab.AzureSettings.DefaultResourceGroup.ResourceGroupName
VMName = $m.ResourceName
FileUri = $uri
TypeHandlerVersion = '{0}.{1}' -f $typehandler.Major, $typehandler.Minor
Name = 'initcustomizations'
Location = (Get-LabAzureDefaultLocation).Location
Run = Split-Path -Path $tempFileName -Leaf
NoWait = $true
}
$Null = Set-AzVMCustomScriptExtension @extArg
}
else
{
Invoke-AzVMRunCommand -ResourceGroupName $rgName -VMName $m.ResourceName -ScriptPath $tempFileName -CommandId 'RunPowerShellScript' -ErrorAction Stop -AsJob
}
}
if ($Wait)
{
Wait-LWLabJob -Job $jobs
$results = $jobs | Receive-Job -Keep -ErrorAction SilentlyContinue -ErrorVariable +AL_AzureWinrmActivationErrors
$failedJobs = $jobs | Where-Object -Property Status -eq 'Failed'
if ($failedJobs)
{
$machineNames = $($($failedJobs).Name -replace "'").ForEach( { $($_ -split '\s')[-1] })
Write-ScreenInfo -Type Error -Message ('Enabling CredSSP on the following lab machines failed: {0}. Check the output of "Get-Job -Id {1} | Receive-Job -Keep" as well as the variable $AL_AzureWinrmActivationErrors' -f $($machineNames -join ','), $($failedJobs.Id -join ','))
}
}
if ($PassThru)
{
$jobs
}
Remove-Item $tempFileName -Force -ErrorAction SilentlyContinue
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Enable-LWAzureWinRm.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,323 |
```powershell
function Wait-LWVMWareRestartVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName,
[double]$TimeoutInMinutes = 15
)
Write-LogFunctionEntry
$prevErrorActionPreference = $Global:ErrorActionPreference
$Global:ErrorActionPreference = 'SilentlyContinue'
$preVerboseActionPreference = $Global:VerbosePreference
$Global:VerbosePreference = 'SilentlyContinue'
$start = Get-Date
Write-PSFMessage "Starting monitoring the servers at '$start'"
$machines = Get-LabVM -ComputerName $ComputerName
$cmd = {
param (
[datetime]$Start
)
$events = Get-EventLog -LogName System -InstanceId 2147489653 -After $Start -Before $Start.AddHours(1)
$events
}
do
{
$azureVmsToWait = foreach ($machine in $machines)
{
$events = Invoke-LabCommand -ComputerName $machine -ActivityName WaitForRestartEvent -ScriptBlock $cmd -ArgumentList $start.Ticks -UseLocalCredential -PassThru
if ($events)
{
Write-PSFMessage "VM '$machine' has been restarted"
}
else
{
$machine
}
Start-Sleep -Seconds 15
}
}
until ($azureVmsToWait.Count -eq 0 -or (Get-Date).AddMinutes(- $TimeoutInMinutes) -gt $start)
$Global:ErrorActionPreference = $prevErrorActionPreference
$Global:VerbosePreference = $preVerboseActionPreference
if ((Get-Date).AddMinutes(- $TimeoutInMinutes) -gt $start)
{
Write-Error -Message "Timeout while waiting for computers to restart. Computers not restarted: $($azureVmsToWait.Name -join ', ')"
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/Wait-LWVMWareRestartVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 451 |
```powershell
function Start-LWAzureVM
{
param (
[Parameter(Mandatory = $true)]
[string[]]$ComputerName,
[int]$DelayBetweenComputers = 0,
[int]$ProgressIndicator = 15,
[switch]$NoNewLine
)
Test-LabHostConnected -Throw -Quiet
Write-LogFunctionEntry
$azureRetryCount = Get-LabConfigurationItem -Name AzureRetryCount
$machines = Get-LabVm -ComputerName $ComputerName -IncludeLinux
$azureVms = Get-LWAzureVm -ComputerName $ComputerName
$stoppedAzureVms = $azureVms | Where-Object { $_.PowerState -ne 'VM running' -and $_.Name -in $machines.ResourceName }
$lab = Get-Lab
$machinesToJoin = @()
if ($stoppedAzureVms)
{
$jobs = foreach ($name in $machines.ResourceName)
{
$vm = $azureVms | Where-Object Name -eq $name
$vm | Start-AzVM -AsJob
}
Wait-LWLabJob -Job $jobs -NoDisplay -ProgressIndicator $ProgressIndicator
}
# Refresh status
$azureVms = Get-LWAzureVm -ComputerName $ComputerName
$azureVms = $azureVms | Where-Object { $_.Name -in $machines.ResourceName }
foreach ($machine in $machines)
{
$vm = $azureVms | Where-Object Name -eq $machine.ResourceName
if ($vm.PowerState -ne 'VM Running')
{
throw "Could not start machine '$machine'"
}
else
{
if ($machine.IsDomainJoined -and -not $machine.HasDomainJoined -and ($machine.Roles.Name -notcontains 'RootDC' -and $machine.Roles.Name -notcontains 'FirstChildDC' -and $machine.Roles.Name -notcontains 'DC'))
{
$machinesToJoin += $machine
}
}
}
if ($machinesToJoin)
{
Write-PSFMessage -Message "Waiting for machines '$($machinesToJoin -join ', ')' to come online"
Wait-LabVM -ComputerName $machinesToJoin -ProgressIndicator $ProgressIndicator -NoNewLine:$NoNewLine
Write-PSFMessage -Message 'Start joining the machines to the respective domains'
Join-LabVMDomain -Machine $machinesToJoin
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/AzureWorkerVirtualMachines/Start-LWAzureVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 559 |
```powershell
function Stop-LWVMWareVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName
)
Write-LogFunctionEntry
foreach ($name in $ComputerName)
{
if (VMware.VimAutomation.Core\Get-VM -Name $name)
{
$result = Shutdown-VMGuest -VM $name -ErrorAction SilentlyContinue -Confirm:$false
if ($result.PowerState -ne "PoweredOff")
{
Write-Error "Could not stop machine '$name'"
}
}
else
{
Write-ScreenInfo "The machine '$name' does not exist on the connected ESX Server" -Type Warning
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/Stop-LWVMWareVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 186 |
```powershell
function Enable-LWVMWareVMRemoting
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param(
[Parameter(Mandatory, Position = 0)]
$ComputerName
)
if ($ComputerName)
{
$machines = Get-LabVM -All | Where-Object Name -in $ComputerName
}
else
{
$machines = Get-LabVM -All
}
$script = {
param ($DomainName, $UserName, $Password)
$VerbosePreference = 'Continue'
$RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
Set-ItemProperty -Path $RegPath -Name AutoAdminLogon -Value 1 -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultUserName -Value $UserName -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultPassword -Value $Password -ErrorAction SilentlyContinue
Set-ItemProperty -Path $RegPath -Name DefaultDomainName -Value $DomainName -ErrorAction SilentlyContinue
Enable-WSManCredSSP -Role Server -Force | Out-Null
}
foreach ($machine in $machines)
{
$cred = $machine.GetCredential((Get-Lab))
try
{
Invoke-LabCommand -ComputerName $machine -ActivityName SetLabVMRemoting -ScriptBlock $script `
-ArgumentList $machine.DomainName, $cred.UserName, $cred.GetNetworkCredential().Password -ErrorAction Stop -Verbose
}
catch
{
Connect-WSMan -ComputerName $machine -Credential $cred
Set-Item -Path "WSMan:\$machine\Service\Auth\CredSSP" -Value $true
Disconnect-WSMan -ComputerName $machine
}
}
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/Enable-LWVMWareVMRemoting.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 423 |
```powershell
function Save-LWVMWareVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName
)
Write-LogFunctionEntry
VMware.VimAutomation.Core\Suspend-VM -VM $ComputerName -ErrorAction SilentlyContinue -Confirm:$false
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/Save-LWVMWareVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 94 |
```powershell
function New-LWVMWareVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
[Cmdletbinding()]
Param (
[Parameter(Mandatory)]
[string]$Name,
[Parameter(Mandatory)]
[string]$ReferenceVM,
[Parameter(Mandatory)]
[string]$AdminUserName,
[Parameter(Mandatory)]
[string]$AdminPassword,
[Parameter(ParameterSetName = 'DomainJoin')]
[string]$DomainName,
[Parameter(Mandatory, ParameterSetName = 'DomainJoin')]
[pscredential]$DomainJoinCredential,
[switch]$AsJob,
[switch]$PassThru
)
Write-LogFunctionEntry
$lab = Get-Lab
#TODO: add logic to determine if machine already exists
<#
if (VMware.VimAutomation.Core\Get-VM -Name $Machine.Name -ErrorAction SilentlyContinue)
{
Write-ProgressIndicatorEnd
Write-ScreenInfo -Message "The machine '$Machine' does already exist" -Type Warning
return $false
}
Write-Verbose "Creating machine with the name '$($Machine.Name)' in the path '$VmPath'"
#>
$folderName = "AutomatedLab_$($lab.Name)"
if (-not (Get-Folder -Name $folderName -ErrorAction SilentlyContinue))
{
New-Folder -Name $folderName -Location VM | out-null
}
$referenceSnapshot = (Get-Snapshot -VM (VMware.VimAutomation.Core\Get-VM $ReferenceVM)).Name | Select-Object -last 1
$parameters = @{
Name = $Name
ReferenceVM = $ReferenceVM
AdminUserName = $AdminUserName
AdminPassword = $AdminPassword
DomainName = $DomainName
DomainCred = $DomainJoinCredential
FolderName = $FolderName
}
if ($AsJob)
{
$job = Start-Job -ScriptBlock {
throw 'Not implemented yet' # TODO: implement
} -ArgumentList $parameters
if ($PassThru)
{
$job
}
}
else
{
$osSpecs = Get-OSCustomizationSpec -Name AutomatedLabSpec -Type NonPersistent -ErrorAction SilentlyContinue
if ($osSpecs)
{
Remove-OSCustomizationSpec -OSCustomizationSpec $osSpecs -Confirm:$false
}
if (-not $parameters.DomainName)
{
$osSpecs = New-OSCustomizationSpec -Name AutomatedLabSpec -FullName $parameters.AdminUserName -AdminPassword $parameters.AdminPassword `
-OSType Windows -Type NonPersistent -OrgName AutomatedLab -Workgroup AutomatedLab -ChangeSid
#$osSpecs = Get-OSCustomizationSpec -Name Standard | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIP -IpAddress $ipaddress -SubnetMask $netmask -DefaultGateway $gateway -Dns $DNS
}
else
{
$osSpecs = New-OSCustomizationSpec -Name AutomatedLabSpec -FullName $parameters.AdminUserName -AdminPassword $parameters.AdminPassword `
-OSType Windows -Type NonPersistent -OrgName AutomatedLab -Domain $parameters.DomainName -DomainCredentials $DomainJoinCredential -ChangeSid
}
$ReferenceVM_int = VMware.VimAutomation.Core\Get-VM -Name $parameters.ReferenceVM
if (-not $ReferenceVM_int)
{
Write-Error "Reference VM '$($parameters.ReferenceVM)' could not be found, cannot create the machine '$($machine.Name)'"
return
}
# Create Linked Clone
$result = VMware.VimAutomation.Core\New-VM `
-Name $parameters.Name `
-ResourcePool $lab.VMWareSettings.ResourcePool `
-Datastore $lab.VMWareSettings.DataStore `
-Location (Get-Folder -Name $parameters.FolderName) `
-OSCustomizationSpec $osSpecs `
-VM $ReferenceVM_int `
-LinkedClone `
-ReferenceSnapshot $referenceSnapshot `
#TODO: logic to switch to full clone for AD recovery scenario's etc.
<# Create full clone
$result = VMware.VimAutomation.Core\New-VM `
-Name $parameters.Name `
-ResourcePool $lab.VMWareSettings.ResourcePool `
-Datastore $lab.VMWareSettings.DataStore `
-Location (Get-Folder -Name $parameters.FolderName) `
-OSCustomizationSpec $osSpecs `
-VM $ReferenceVM_int
#>
}
if ($PassThru)
{
$result
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/New-LWVMWareVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 1,042 |
```powershell
function Start-LWVMWareVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory = $true)]
[string[]]$ComputerName,
[int]$DelayBetweenComputers = 0
)
Write-LogFunctionEntry
foreach ($name in $ComputerName)
{
$vm = $null
$vm = VMware.VimAutomation.Core\Get-VM -Name $name
if ($vm)
{
VMware.VimAutomation.Core\Start-VM $vm -ErrorAction SilentlyContinue | out-null
$result = VMware.VimAutomation.Core\Get-VM $vm
if ($result.PowerState -ne "PoweredOn")
{
Write-Error "Could not start machine '$name'"
}
}
Start-Sleep -Seconds $DelayBetweenComputers
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/Start-LWVMWareVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 208 |
```powershell
function Remove-LWVMWareVM
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
Param (
[Parameter(Mandatory)]
[string]$ComputerName,
[switch]$AsJob,
[switch]$PassThru
)
Write-LogFunctionEntry
if ($AsJob)
{
$job = Start-Job -ScriptBlock {
param (
[Parameter(Mandatory)]
[hashtable]$ComputerName
)
Add-PSSnapin -Name VMware.VimAutomation.Core, VMware.VimAutomation.Vds
$vm = VMware.VimAutomation.Core\Get-VM -Name $ComputerName
if ($vm)
{
if ($vm.PowerState -eq "PoweredOn")
{
VMware.VimAutomation.Core\Stop-VM -VM $vm -Confirm:$false
}
VMware.VimAutomation.Core\Remove-VM -DeletePermanently -VM $ComputerName -Confirm:$false
}
} -ArgumentList $ComputerName
if ($PassThru)
{
$job
}
}
else
{
$vm = VMware.VimAutomation.Core\Get-VM -Name $ComputerName
if ($vm)
{
if ($vm.PowerState -eq "PoweredOn")
{
VMware.VimAutomation.Core\Stop-VM -VM $vm -Confirm:$false
}
VMware.VimAutomation.Core\Remove-VM -DeletePermanently -VM $ComputerName -Confirm:$false
}
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/Remove-LWVMWareVM.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 350 |
```powershell
function Get-LWVMWareVMStatus
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseCompatibleCmdlets", "", Justification="Not relevant on Linux")]
param (
[Parameter(Mandatory)]
[string[]]$ComputerName
)
Write-LogFunctionEntry
$result = @{ }
foreach ($name in $ComputerName)
{
$vm = VMware.VimAutomation.Core\Get-VM -Name $name
if ($vm)
{
if ($vm.PowerState -eq 'PoweredOn')
{
$result.Add($vm.Name, 'Started')
}
elseif ($vm.PowerState -eq 'PoweredOff')
{
$result.Add($vm.Name, 'Stopped')
}
else
{
$result.Add($vm.Name, 'Unknown')
}
}
}
$result
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/VMWareWorkerVirtualMachines/Get-LWVMWareVMStatus.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 191 |
```powershell
function Uninstall-LWHypervWindowsFeature
{
[cmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[AutomatedLab.Machine[]]$Machine,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string[]]$FeatureName,
[switch]$IncludeManagementTools,
[switch]$UseLocalCredential,
[switch]$AsJob,
[switch]$PassThru
)
Write-LogFunctionEntry
$activityName = "Uninstall Windows Feature(s): '$($FeatureName -join ', ')'"
$result = @()
foreach ($m in $Machine)
{
if ($m.OperatingSystem.Version -ge [System.Version]'6.2')
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
$cmd = [scriptblock]::Create("Disable-WindowsOptionalFeature -Online -FeatureName $($FeatureName -join ', ') -NoRestart -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
else
{
$cmd = [scriptblock]::Create("Uninstall-WindowsFeature $($FeatureName -join ', ') -IncludeManagementTools:`$$IncludeManagementTools -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
if ($m.OperatingSystem.Installation -eq 'Client')
{
if ($FeatureName.Count -gt 1)
{
foreach ($feature in $FeatureName)
{
$cmd = [scriptblock]::Create("DISM /online /disable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("DISM /online /disable-feature /featurename:$($feature)")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
else
{
$cmd = [scriptblock]::Create("`$null;Import-Module -Name ServerManager; Remove-WindowsFeature $($FeatureName -join ', ') -WarningAction SilentlyContinue")
$result += Invoke-LabCommand -ComputerName $m -ActivityName $activityName -NoDisplay -ScriptBlock $cmd -UseLocalCredential:$UseLocalCredential -AsJob:$AsJob -PassThru:$PassThru
}
}
}
if ($PassThru)
{
$result
}
Write-LogFunctionExit
}
``` | /content/code_sandbox/AutomatedLabWorker/functions/Core/Uninstall-LWHypervWindowsFeature.ps1 | powershell | 2016-08-23T00:08:15 | 2024-08-16T12:01:05 | AutomatedLab | AutomatedLab/AutomatedLab | 1,988 | 701 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.