text:
Option Strict Off
Option Explicit On

Imports System.Xml
Imports System.Web.Configuration
Imports System.Data.SqlClient
Imports System.Reflection
Imports System.Collections.Generic

Partial Public Class Cms
    Partial Public Class Membership

#Region "Declarations"

        Dim myWeb As Protean.Cms
        Public Event OnError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs)
        Public Event OnErrorWithWeb(ByRef myweb As Protean.Cms, ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs)
        Private Const mcModuleName As String = "Eonic.EonicWeb.Membership.Membership"

#End Region

#Region "Public Procedures"

        Public Sub New(ByRef oWeb As Protean.Cms)
            Try
                myWeb = oWeb
            Catch ex As Exception

            End Try
        End Sub

        Public Function AccountResetLink(ByVal AccountID As Integer) As String
            Try
                'RJP 7 Nov 2012. Added LCase to MembershipEncryption.
                Dim cLink As String = Trim(Protean.Tools.Encryption.HashString(UCase(Now()), LCase(myWeb.moConfig("MembershipEncryption")), True))
                Dim cSQL As String = "UPDATE tblDirectory SET cDirPassword = '" & cLink & "' WHERE nDirKey = " & AccountID
                cLink = Protean.Tools.Text.AscString(cLink)
                Debug.WriteLine(cLink)
                If IsNumeric(myWeb.moDbHelper.ExeProcessSql(cSQL)) Then
                    Return cLink
                Else
                    Return ""
                End If
            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "AccountResetLink", ex, ""))
                Return ""
            End Try
        End Function

        ''' <summary>
        ''' 'We need to activate the link create a hash, We store the activation hash in the UserXML
        ''' </summary>
        ''' <param name="AccountID"></param>
        ''' <returns></returns>
        ''' <remarks>Cannot store in password field because we need this, We could store in the audit description, allthough don't think this is indexed. Storing in the userXml would be inefficient to search however it could be useful because it is contained in the email</remarks>

        Public Function AccountActivateLink(ByVal AccountID As Integer) As String
            Try
                Dim oGuid As System.Guid = System.Guid.NewGuid()

                Dim cLink As String = oGuid.ToString

                Dim oUserXml As New XmlDocument
                oUserXml.AppendChild(oUserXml.CreateElement("instance"))
                oUserXml.DocumentElement.InnerXml = myWeb.moDbHelper.getObjectInstance(dbHelper.objectTypes.Directory, AccountID)
                Dim oUserElmt As XmlElement = oUserXml.DocumentElement.SelectSingleNode("tblDirectory/cDirXml/User")
                Dim ActivationKeyElmt As XmlElement = oUserXml.CreateElement("ActivationKey")

                ActivationKeyElmt.InnerText = cLink

                oUserElmt.AppendChild(ActivationKeyElmt)
                myWeb.moDbHelper.setObjectInstance(dbHelper.objectTypes.Directory, oUserXml.DocumentElement, AccountID)

                Return cLink

            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "AccountActivateLink", ex, ""))
                Return ""
            End Try
        End Function

        Public Function DecryptResetLink(ByVal AccountID As Integer, ByVal EncryptedString As String) As Integer
            Try
                EncryptedString = Protean.Tools.Text.DeAscString(EncryptedString)

                Dim cSQL As String = "SELECT tblDirectory.nDirKey FROM tblDirectory INNER JOIN tblAudit ON tblDirectory.nAuditId = tblAudit.nAuditKey WHERE cDirPassword = '" & SqlFmt(EncryptedString) & "' AND nDirKey = " & AccountID
                Return myWeb.moDbHelper.GetDataValue(cSQL, , , 0)
            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "DecryptResetLink", ex, ""))
                Return 0
            End Try
        End Function

        Public Function CheckPasswordHistory(ByVal AccountID As Integer, ByVal cPassword As String) As Boolean
            Dim odr As SqlDataReader
            Dim valid As Boolean = True
            Try

                If LCase(myWeb.moConfig("MembershipEncryption")) = "md5salt" Then
                    Dim cSalt As String = Protean.Tools.Encryption.generateSalt
                    Dim inputPassword As String = String.Concat(cSalt, cPassword) 'Take the users password and add the salt at the front
                    'Note leave the value below hard coded md5.
                    Dim md5Password As String = Protean.Tools.Encryption.HashString(inputPassword, "md5", True) 'Md5 the marged string of the password and salt
                    Dim resultPassword As String = String.Concat(md5Password, ":", cSalt) 'Adds the salt to the end of the hashed password
                    cPassword = resultPassword 'Store the resultant password with salt in the database
                Else

                    cPassword = Protean.Tools.Encryption.HashString(cPassword, LCase(myWeb.moConfig("MembershipEncryption")), True) 'plain - md5 - sha1

                End If

                'ensure the password is XML safe
                Dim oConvDoc As New XmlDocument
                Dim oConvElmt As XmlElement = oConvDoc.CreateElement("PW")
                oConvElmt.InnerText = cPassword
                cPassword = oConvElmt.InnerXml

                Dim moPolicy As XmlElement
                moPolicy = WebConfigurationManager.GetWebApplicationSection("protean/PasswordPolicy")
                Dim nHistoricPasswordCount As Integer = CInt("0" & moPolicy.FirstChild.SelectSingleNode("blockHistoricPassword").InnerText)

                Dim sSql2 As String = "select cActivityDetail as password, dDatetime from tblActivityLog where nActivityType=" & dbHelper.ActivityType.HistoricPassword & " and nUserDirId = " & AccountID _
                & " Order By dDateTime Desc"

                odr = myWeb.moDbHelper.getDataReader(sSql2)
                While odr.Read
                    If nHistoricPasswordCount > 0 And cPassword = odr("password") Then
                        valid = False
                    End If
                    nHistoricPasswordCount = nHistoricPasswordCount - 1
                End While

                Return valid

            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "CheckPasswordHistory", ex, ""))
                Return False
            End Try
        End Function

        Public Function ReactivateAccount(ByVal AccountID As Integer, ByVal cPassword As String) As Boolean
            Try

                ' cPassword = Protean.Tools.Encryption.HashString(cPassword, myWeb.moConfig("MembershipEncryption"), True)

                'RJP 7 Nov 2012. Added LCase to MembershipEncryption. Note leave the value below for md5Password hard coded as md5.
                If LCase(myWeb.moConfig("MembershipEncryption")) = "md5salt" Then
                    Dim cSalt As String = Protean.Tools.Encryption.generateSalt
                    Dim inputPassword As String = String.Concat(cSalt, cPassword) 'Take the users password and add the salt at the front
                    'Note leave the value below hard coded md5.
                    Dim md5Password As String = Protean.Tools.Encryption.HashString(inputPassword, "md5", True) 'Md5 the marged string of the password and salt
                    Dim resultPassword As String = String.Concat(md5Password, ":", cSalt) 'Adds the salt to the end of the hashed password
                    cPassword = resultPassword 'Store the resultant password with salt in the database
                Else
                    cPassword = Protean.Tools.Encryption.HashString(cPassword, LCase(myWeb.moConfig("MembershipEncryption")), True) 'plain - md5 - sha1
                End If

                'ensure the password is XML safe
                Dim oConvDoc As New XmlDocument
                Dim oConvElmt As XmlElement = oConvDoc.CreateElement("PW")
                oConvElmt.InnerText = cPassword
                cPassword = oConvElmt.InnerXml

                Dim moPolicy As XmlElement
                moPolicy = WebConfigurationManager.GetWebApplicationSection("protean/PasswordPolicy")
                Dim nHistoricPasswordCount As Integer = CInt("0" & moPolicy.FirstChild.SelectSingleNode("blockHistoricPassword").InnerText)
                If nHistoricPasswordCount > 0 Then
                    myWeb.moDbHelper.logActivity(dbHelper.ActivityType.HistoricPassword, AccountID, 0, , cPassword)
                End If

                Dim cSQL As String = "UPDATE tblDirectory SET cDirPassword = '" & cPassword & "' WHERE nDirKey = " & AccountID
                If myWeb.moDbHelper.ExeProcessSql(cSQL) > 0 Then
                    Return True
                Else
                    Return False
                End If
            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ReactivateAccount", ex, ""))
                Return False
            End Try
        End Function

        Public Function ActivateAccount(ByVal cLink As String) As Boolean
            Try
                Dim userId As Long

                'lets get the userId form the hash supplied
                Dim cSQL As String = "SELECT tblDirectory.nDirKey FROM tblDirectory INNER JOIN tblAudit ON tblDirectory.nAuditId = tblAudit.nAuditKey WHERE cDirXml LIKE '%<ActivationKey>" & cLink & "</ActivationKey>%'"
                userId = myWeb.moDbHelper.GetDataValue(cSQL, , , 0)

                If userId > 0 Then
                    'change the account status
                    myWeb.moDbHelper.setObjectStatus(dbHelper.objectTypes.Directory, dbHelper.Status.Live, userId)
                    'remove the activation key from userXML
                    Dim oUserXml As New XmlDocument
                    Dim oUserInstance As XmlElement = oUserXml.CreateElement("Instance")
                    oUserXml.AppendChild(oUserInstance)
                    oUserInstance.InnerXml = myWeb.moDbHelper.getObjectInstance(dbHelper.objectTypes.Directory, userId)
                    Dim ActivationKeyElmt As XmlElement
                    ActivationKeyElmt = oUserInstance.FirstChild.SelectSingleNode("cDirXml/User/ActivationKey")
                    ActivationKeyElmt.ParentNode.RemoveChild(ActivationKeyElmt)
                    myWeb.moDbHelper.setObjectInstance(dbHelper.objectTypes.Directory, oUserXml.DocumentElement, userId)

                    myWeb.moDbHelper.CommitLogToDB(dbHelper.ActivityType.Register, userId, myWeb.moSession.SessionID, Now, 0, 0, "Activate")
                    Select Case myWeb.moConfig("ActivateBehaviour")
                        Case "LogonReload"
                            myWeb.mnUserId = userId
                            If Not myWeb.moSession Is Nothing Then
                                myWeb.moSession("nUserId") = myWeb.mnUserId
                            End If
                            'Add subscribe to subscribe to the subscription if we have one
                            If myWeb.mnArtId > 0 Then
                                myWeb.msRedirectOnEnd = myWeb.mcPageURL & "?artid=" & myWeb.mnArtId & "&ewCmd=Subscribe"
                            Else

                                myWeb.msRedirectOnEnd = myWeb.mcPageURL & "?ewCmd=Subscribe"
                            End If

                        Case "LogonRedirect"
                            'todo
                        Case Else
                            'do nuffin
                    End Select
                    Return True

                Else
                    Return False
                End If

            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ReactivateAccount", ex, ""))
                Return False
            End Try
        End Function

#End Region

#Region "Secure Membership"

        Public Function SetCookie(ByVal Name As String, ByVal Value As Object, Optional ByVal Expires As Date = Nothing) As System.Web.HttpCookie
            Try
                Dim Cookie As System.Web.HttpCookie = myWeb.moResponse.Cookies(Name)
                If Cookie Is Nothing Then Cookie = New System.Web.HttpCookie(Name)
                Cookie.Value = Value
                If myWeb.moConfig("SecureMembershipDomain") <> "" Then
                    Cookie.Domain = myWeb.moConfig("SecureMembershipDomain")
                End If

                If Expires = Nothing Then Cookie.Expires = Expires
                myWeb.moResponse.Cookies.Add(Cookie)
                Return Cookie
            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "SetCookie", ex, ""))
                Return Nothing
            End Try
        End Function

        Public Function CookieValue(ByVal Name As String, Optional ByVal ValueIfNothing As Object = Nothing) As Object
            Try
                If Not myWeb.moRequest.Cookies(Name) Is Nothing Then
                    Return myWeb.moRequest.Cookies(Name).Value
                Else
                    Return ValueIfNothing
                End If
            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "CookieValue", ex, ""))
                Return Nothing
            End Try
        End Function

        Public Sub SecureMembershipProcess(ByVal cForceCommand As String)
            Try
                'Variables
                Dim ASPSessionName As String = IIf(myWeb.moConfig("ASPSessionName") = "", "ASP.NET_SessionId", myWeb.moConfig("ASPSessionName"))
                Dim UserCookieName As String = IIf(myWeb.moConfig("UserCookieName") = "", "nUserId", myWeb.moConfig("UserCookieName"))
                Dim SecureMembershipAddress As String = myWeb.moConfig("SecureMembershipAddress")
                Dim SecureMembershipDomain As String = myWeb.moConfig("SecureMembershipDomain")

                'Session Cookie
                System.Web.HttpContext.Current.Response.Cookies(ASPSessionName).Value = System.Web.HttpContext.Current.Session.SessionID
                If SecureMembershipDomain <> "" Then
                    System.Web.HttpContext.Current.Response.Cookies(ASPSessionName).Domain = SecureMembershipDomain
                End If
                'Path
                Dim cPath As String = "" & myWeb.moRequest.QueryString("path")
                For i As Integer = 0 To myWeb.moRequest.QueryString.Count - 1
                    If Not myWeb.moRequest.QueryString.Keys(i) = "path" Then
                        cPath &= "&" & myWeb.moRequest.QueryString.Keys(i)
                        cPath &= "=" & myWeb.moRequest.QueryString.Item(i)
                    End If
                Next
                'Check Request Cookie first
                Dim nCookieUser As Integer = CookieValue(UserCookieName, -1)
                'Check what we are doing
                If LCase(cForceCommand) = "logoff" Then
                    'redirect to the logoff with no cookie
                    SetCookie(UserCookieName, 0, Now.AddMinutes(-20))
                    If Not LCase(cPath).Contains(LCase("ewCmd=LogOff")) Then
                        If cPath.Contains("?") Then
                            cPath &= "&"
                        Else
                            cPath &= "?"
                        End If
                        cPath &= "ewCmd=LogOff"
                    End If
                    'Ultimate logoff cmd
                    myWeb.moSession("nUserId") = 0
                    myWeb.moSession.Abandon()
                    myWeb.mnUserId = 0
                    myWeb.msRedirectOnEnd = myWeb.moConfig("SecureMembershipAddress") & myWeb.moConfig("ProjectPath") & "/"
                ElseIf LCase(cForceCommand) = "logoffimpersonate" Then
                    'redirect to the logoff with no cookie
                    SetCookie(UserCookieName, 0, Now.AddMinutes(-20))
                    myWeb.moSession("nUserId") = 0
                    myWeb.mnUserId = 0
                ElseIf nCookieUser > 0 Then
                    'logon with this user
                    myWeb.mnUserId = nCookieUser
                End If

                'Check to see if we need to do a redirect
                Dim cHost As String = IIf(myWeb.moRequest.ServerVariables("HTTPS") = "on", "https://", "http://") & myWeb.moRequest.ServerVariables("HTTP_HOST")
                Dim oVariants As New Hashtable
                oVariants.Add("0", cHost)
                oVariants.Add("1", cHost & "/")
                oVariants.Add("2", cHost & myWeb.moConfig("ProjectPath"))
                oVariants.Add("3", cHost & myWeb.moConfig("ProjectPath") & "/")

                'oVariants.Add("2", "http://" & cHost)
                'oVariants.Add("3", "http://" & cHost & "/")

                'If oVariants.ContainsValue(SecureMembershipAddress) And myWeb.mnUserId = 0 Then
                '    If Left(cPath, 1) = "/" And Right(myWeb.moConfig("HomeUrl"), 1) = "/" Then cPath = cPath.Remove(0, 1)
                '    myWeb.moResponse.Redirect(myWeb.moConfig("HomeUrl") & cPath)
                'Else
                If Not oVariants.ContainsValue(SecureMembershipAddress) And (myWeb.mnUserId > 0 Or myWeb.mbAdminMode Or LCase(myWeb.moRequest("ewCmd")) = "ar") Then
                    SetCookie(UserCookieName, myWeb.mnUserId, Now.AddMinutes(20))
                    If Not Right(SecureMembershipAddress, 1) = "/" Then SecureMembershipAddress &= "/"
                    If Left(cPath, 1) = "/" And Right(SecureMembershipAddress, 1) = "/" Then cPath = cPath.Remove(0, 1)
                    If cPath.StartsWith("&") Then cPath = "?" & cPath.Substring(1)
                    myWeb.msRedirectOnEnd = SecureMembershipAddress & cPath
                    ' myWeb.moResponse.Redirect(SecureMembershipAddress & cPath)
                ElseIf oVariants.ContainsValue(SecureMembershipAddress) And myWeb.mnUserId > 0 Then
                    If Not myWeb.moPageXml Is Nothing Then
                        If Not myWeb.moPageXml.DocumentElement Is Nothing Then
                            myWeb.moPageXml.DocumentElement.SetAttribute("baseUrl", SecureMembershipAddress & myWeb.moConfig("ProjectPath") & "/")
                        End If
                    End If
                    SetCookie(UserCookieName, myWeb.mnUserId, Now.AddMinutes(20))
                ElseIf myWeb.moRequest.ServerVariables("HTTPS") = "on" Then
                    If Not myWeb.moPageXml Is Nothing Then
                        If Not myWeb.moPageXml.DocumentElement Is Nothing Then
                            'don't want this for everything just the logon form
                            myWeb.moPageXml.DocumentElement.SetAttribute("baseUrl", SecureMembershipAddress & myWeb.moConfig("ProjectPath"))
                        End If
                    End If
                End If

            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "SecureMembershipProcess", ex, ""))
            End Try
        End Sub

        Public Sub ProviderActions(ByRef myWeb As Protean.Cms, ByVal actionName As String)
            Dim sProcessInfo As String = ""
            Try

                Dim castObject As Object = WebConfigurationManager.GetWebApplicationSection("protean/membershipProviders")
                Dim moPrvConfig As Protean.ProviderSectionHandler = castObject

                Dim ourProvider As Object
                For Each ourProvider In moPrvConfig.Providers
                    If Not ourProvider.parameters(actionName) Is Nothing Then
                        Dim calledType As Type
                        Dim assemblyInstance As [Assembly]

                        If ourProvider.parameters("path") <> "" Then
                            assemblyInstance = [Assembly].LoadFrom(myWeb.goServer.MapPath(ourProvider.parameters("path")))
                        Else
                            assemblyInstance = [Assembly].Load(ourProvider.Type)
                        End If
                        If ourProvider.parameters("rootClass") = "" Then
                            calledType = assemblyInstance.GetType("Protean.Providers.Membership." & ourProvider.Name & "Tools.Actions", True)
                        Else
                            calledType = assemblyInstance.GetType(ourProvider.parameters("rootClass") & ".Providers.Membership." & ourProvider.Name & "Tools.Actions", True)
                        End If

                        Dim o As Object = Activator.CreateInstance(calledType)

                        Dim args(0) As Object
                        args(0) = myWeb

                        calledType.InvokeMember(ourProvider.parameters(actionName), BindingFlags.InvokeMethod, Nothing, o, args)

                    End If
                Next

            Catch ex As Exception
                RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "ProviderActions", ex, ""))
            End Try
        End Sub

#End Region

#Region "Module Behaviour"

        Public Class Modules

            Public Event OnError(ByVal sender As Object, ByVal e As Protean.Tools.Errors.ErrorEventArgs)
            Private Const mcModuleName As String = "Protean.Cms.Membership.Modules"

            Public Sub New()

                'do nowt

            End Sub

            'sReturnValue = "LogOn"
            'moDbHelper.logActivity(dbHelper.ActivityType.Logon, mnUserId, mnPageId, mnArtId)
            ' myWeb.moDbHelper.CommitLogToDB(dbHelper.ActivityType.Logon, myWeb.mnUserId, myWeb.moSession.SessionID, Now, 0, 0, "")

            Public Sub Logon(ByRef myWeb As Protean.Cms, ByRef oContentNode As XmlElement)
                Try
                    Dim adXfm As Object = myWeb.getAdminXform()
                    adXfm.open(myWeb.moPageXml)
                    Dim oXfmElmt As XmlElement
                    Dim sReturnValue As String = Nothing
                    Dim cLogonCmd As String = ""

                    If myWeb.mnUserId = 0 And (myWeb.moRequest("ewCmd") <> "passwordReminder" And myWeb.moRequest("ewCmd") <> "ActivateAccount") Then

                        oXfmElmt = adXfm.xFrmUserLogon()
                        Dim bAdditionalChecks As Boolean = False
                        If Not (adXfm.valid) Then
                            ' Call in additional authentication checks
                            If myWeb.moConfig("AlternativeAuthentication") = "On" Then
                                bAdditionalChecks = myWeb.AlternativeAuthentication()
                            End If
                        End If

                        If adXfm.valid Or bAdditionalChecks Then
                            myWeb.moContentDetail = Nothing
                            'mnUserId = adXfm.mnUserId
                            If Not myWeb.moSession Is Nothing Then myWeb.moSession("nUserId") = myWeb.mnUserId
                            If myWeb.moRequest("cRemember") = "true" Then
                                Dim oCookie As System.Web.HttpCookie = New System.Web.HttpCookie("RememberMe")
                                oCookie.Value = myWeb.mnUserId
                                oCookie.Expires = DateAdd(DateInterval.Day, 60, Now())
                                myWeb.moResponse.Cookies.Add(oCookie)
                            End If
                            'Now we want to reload as permissions have changed
                            If Not myWeb.moSession Is Nothing Then
                                If Not myWeb.moSession("cLogonCmd") Is Nothing Then
                                    cLogonCmd = Split(myWeb.moSession("cLogonCmd"), "=")(0)
                                    If myWeb.mcOriginalURL.Contains(cLogonCmd & "=") Then
                                        cLogonCmd = ""
                                    Else
                                        If myWeb.mcOriginalURL.Contains("=") Then
                                            cLogonCmd = "&" & myWeb.moSession("cLogonCmd")
                                        Else
                                            cLogonCmd = "?" & myWeb.moSession("cLogonCmd")
                                        End If
                                    End If
                                End If
                            End If
                            myWeb.moSession("RedirectReason") = "logonSuccessful"

                            Dim oMembership As New Protean.Cms.Membership(myWeb)
                            oMembership.ProviderActions(myWeb, "logonAction")

                            myWeb.logonRedirect(cLogonCmd)
                        Else
                            oContentNode.InnerXml = oXfmElmt.InnerXml
                        End If

                    ElseIf myWeb.moRequest("ewCmd") = "passwordReminder" Then
                        'RJP 7 Nov 2012. Amended to use Lower Case to prevent against case sensitive entries in Protean.Cms.Config.
                        Select Case LCase(myWeb.moConfig("MembershipEncryption"))
                            Case "md5", "sha1", "sha256"
                                oXfmElmt = adXfm.xFrmResetAccount()
                            Case Else
                                oXfmElmt = adXfm.xFrmPasswordReminder()
                        End Select
                        oContentNode.InnerXml = oXfmElmt.InnerXml

                    ElseIf myWeb.moRequest("ewCmd") = "ActivateAccount" Then

                        oXfmElmt = adXfm.xFrmActivateAccount()
                        oContentNode.InnerXml = oXfmElmt.InnerXml

                    End If

                Catch ex As Exception
                    RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "Logon", ex, ""))
                End Try
            End Sub

            Public Sub Register(ByRef myWeb As Protean.Cms, ByRef oContentNode As XmlElement)
                Try
                    myWeb.bPageCache = False
                    Dim mnUserId As Long = myWeb.mnUserId
                    Dim mbAdminMode As Boolean = myWeb.mbAdminMode
                    Dim moPageXml As XmlDocument = myWeb.moPageXml
                    Dim moDbHelper As Protean.Cms.dbHelper = myWeb.moDbHelper
                    Dim moSession As System.Web.SessionState.HttpSessionState = myWeb.moSession
                    Dim moConfig As System.Collections.Specialized.NameValueCollection = myWeb.moConfig
                    Dim moRequest As System.Web.HttpRequest = myWeb.moRequest

                    Dim goServer As System.Web.HttpServerUtility = myWeb.goServer

                    Dim cLogonCmd As String = ""
                    Dim bRedirectStarted As Boolean = False
                    Dim oXfmElmt As XmlElement
                    Dim sProcessInfo As String

                    Dim AccountCreateForm As String = "UserRegister"
                    Dim AccountUpdateForm As String = "UserMyAccount"

                    If oContentNode.GetAttribute("accountCreateFormName") <> "" Then AccountCreateForm = oContentNode.GetAttribute("accountCreateFormName")
                    If oContentNode.GetAttribute("accountUpdateFormName") <> "" Then AccountUpdateForm = oContentNode.GetAttribute("accountUpdateFormName")

                    Dim bLogon As Boolean = False

                    Dim oMembershipProv As New Providers.Membership.BaseProvider(myWeb, myWeb.moConfig("MembershipProvider"))
                    Dim adXfm As Object = oMembershipProv.AdminXforms
                    Dim bRedirect As Boolean = True

                    ' OAuth Functionality

                    If Not moRequest("oAuthResp") <> "" Then
                        If moRequest("oAuthReg") <> "" And myWeb.msRedirectOnEnd = "" Then
                            Dim sRedirectPath = ""
                            Dim appId = ""
                            Dim redirectURI = "https://" & moRequest.ServerVariables("SERVER_NAME") & myWeb.mcPageURL & "?oAuthResp=" & moRequest("oAuthReg")
                            Select Case moRequest("oAuthReg")
                                Case "facebook"
                                    sRedirectPath = "https://www.facebook.com/v2.8/dialog/oauth?"
                                    appId = moConfig("OauthFacebookId")
                                    sRedirectPath = sRedirectPath & "client_id=" & appId & "&redirect_uri=" & redirectURI
                                Case "twitter"
                                    Dim twApi As New Integration.Directory.Twitter(myWeb)
                                    twApi.twitterConsumerKey = moConfig("OauthTwitterId")
                                    twApi.twitterConsumerSecret = moConfig("OauthTwitterKey")
                                    sRedirectPath = twApi.GetRequestToken()
                            End Select
                            myWeb.msRedirectOnEnd = sRedirectPath
                        Else

                        End If
                    Else
                        Select Case moRequest("oAuthResp")
                            Case "facebook"
                                Dim redirectURI = "http://" & moRequest.ServerVariables("SERVER_NAME") & myWeb.mcPageURL & "?oAuthResp=facebook"
                                sProcessInfo = "Facebook Response"
                                Dim fbClient As New Protean.Integration.Directory.Facebook(myWeb, moConfig("OauthFacebookId"), moConfig("OauthFacebookKey"))
                                Dim fbUsers As List(Of Protean.Integration.Directory.Facebook.User)
                                fbUsers = fbClient.GetFacebookUserData(moRequest("code"), redirectURI)
                                sProcessInfo = fbUsers(0).first_name & " " & fbUsers(0).last_name

                                mnUserId = fbClient.CreateUser(fbUsers(0))

                                If Not moSession Is Nothing Then moSession("nUserId") = mnUserId
                                moDbHelper.CommitLogToDB(dbHelper.ActivityType.Register, mnUserId, moSession.SessionID, Now, 0, 0, "First Logon")

                                bLogon = True

                            Case "twitter"
                                sProcessInfo = "Twitter Response"
                                Dim twApi As New Integration.Directory.Twitter(myWeb)
                                twApi.twitterConsumerKey = moConfig("OauthTwitterId")
                                twApi.twitterConsumerSecret = moConfig("OauthTwitterKey")
                                'Get twitter user
                                Dim twUsers As List(Of Protean.Integration.Directory.Twitter.User)

                        End Select
                        If mnUserId > 0 Then

                        End If

                    End If

                    ' If not in admin mode then base our choice on whether the user is logged in.
                    ' If in Admin Mode, then present it as WYSIWYG
                    If (Not (myWeb.mbAdminMode) And myWeb.mnUserId > 0) Then

                        Dim oContentForm As XmlElement = myWeb.moPageXml.SelectSingleNode("descendant-Or-self::Content[@type='xform' and @name='UserMyAccount']")
                        If oContentForm Is Nothing Then
                            oXfmElmt = adXfm.xFrmEditDirectoryItem(myWeb.mnUserId, "User", , AccountUpdateForm)
                        Else
                            oXfmElmt = adXfm.xFrmEditDirectoryItem(myWeb.mnUserId, "User", , AccountUpdateForm, oContentForm.OuterXml)
                            If Not myWeb.mbAdminMode Then oContentForm.ParentNode.RemoveChild(oContentForm)
                        End If
                        oContentNode.InnerXml = oXfmElmt.InnerXml

                    Else

                        Dim oContentForm As XmlElement = moPageXml.SelectSingleNode("descendant-or-self::Content[@type='xform' and @name='UserRegister']")
                        If oContentForm Is Nothing Then
                            oXfmElmt = adXfm.xFrmEditDirectoryItem(mnUserId, "User", , AccountCreateForm)
                        Else
                            oXfmElmt = adXfm.xFrmEditDirectoryItem(mnUserId, "User", , AccountCreateForm, oContentForm.OuterXml)
                            If Not mbAdminMode Then oContentForm.ParentNode.RemoveChild(oContentForm)
                        End If

                        If myWeb.moConfig("SecureMembershipAddress") <> "" And myWeb.mbAdminMode = False Then
                            Dim oSubElmt As XmlElement = adXfm.moXformElmt.SelectSingleNode("descendant::submission")
                            oSubElmt.SetAttribute("action", myWeb.moConfig("SecureMembershipAddress") & myWeb.mcPagePath)
                        End If

                        ' ok if the user is valid we then need to handle what happens next.
                        If adXfm.valid Then

                            Select Case myWeb.moConfig("RegisterBehaviour")

                                Case "validateByEmail"
                                    'don't redirect because we want to reuse this form
                                    bRedirect = False

                                    'say thanks for registering and update the form

                                    'hide the current form
                                    Dim oFrmGrp As XmlElement = adXfm.moXformElmt.SelectSingleNode("group")
                                    oFrmGrp.SetAttribute("class", "hidden")
                                    'create a new note
                                    Dim oFrmGrp2 As XmlElement = adXfm.addGroup(adXfm.moXformElmt, "validateByEmail")
                                    adXfm.addNote(oFrmGrp2, xForm.noteTypes.Hint, "<span class=""msg-1029"">Thanks for registering you have been sent an email with a link you must click to activate your account</span>", True)

                                    'lets get the new userid from the instance
                                    mnUserId = adXfm.instance.SelectSingleNode("tblDirectory/nDirKey").InnerText

                                    'first we set the user account to be pending
                                    moDbHelper.setObjectStatus(dbHelper.objectTypes.Directory, dbHelper.Status.Pending, mnUserId)

                                    Dim oMembership As New Protean.Cms.Membership(myWeb)
                                    AddHandler oMembership.OnError, AddressOf myWeb.OnComponentError
                                    oMembership.AccountActivateLink(mnUserId)

                                    moDbHelper.CommitLogToDB(dbHelper.ActivityType.Register, mnUserId, moSession.SessionID, Now, 0, 0, "Send Activation")

                                Case Else ' Auto logon
                                    mnUserId = adXfm.instance.SelectSingleNode("tblDirectory/nDirKey").InnerText
                                    If Not moSession Is Nothing Then moSession("nUserId") = mnUserId

                                    moDbHelper.CommitLogToDB(dbHelper.ActivityType.Register, mnUserId, moSession.SessionID, Now, 0, 0, "First Logon")

                                    bLogon = True

                            End Select

                            'send registration confirmation
                            Dim xsltPath As String = "/xsl/email/registration.xsl"

                            If IO.File.Exists(goServer.MapPath(xsltPath)) Then
                                Dim oUserElmt As XmlElement = moDbHelper.GetUserXML(mnUserId)

                                Dim oElmtPwd As XmlElement = moPageXml.CreateElement("Password")
                                oElmtPwd.InnerText = moRequest("cDirPassword")
                                oUserElmt.AppendChild(oElmtPwd)

                                oUserElmt.SetAttribute("Url", myWeb.mcOriginalURL)

                                Dim oUserEmail As XmlElement = oUserElmt.SelectSingleNode("Email")
                                Dim fromName As String = moConfig("SiteAdminName")
                                Dim fromEmail As String = moConfig("SiteAdminEmail")
                                Dim recipientEmail As String = ""
                                If Not oUserEmail Is Nothing Then recipientEmail = oUserEmail.InnerText
                                Dim SubjectLine As String = "Your Registration Details"
                                Dim oMsg As Messaging = New Messaging(myWeb.msException)
                                'send an email to the new registrant
                                If Not recipientEmail = "" Then sProcessInfo = oMsg.emailer(oUserElmt, xsltPath, fromName, fromEmail, recipientEmail, SubjectLine, "Message Sent", "Message Failed")

                                'send an email to the webadmin
                                If moConfig("RegistrationAlertEmail") = "" Then
                                    recipientEmail = moConfig("SiteAdminEmail")
                                Else
                                    recipientEmail = moConfig("RegistrationAlertEmail")
                                End If

                                If IO.File.Exists(goServer.MapPath(moConfig("ProjectPath") & "/xsl/email/registrationAlert.xsl")) Then
                                        sProcessInfo = oMsg.emailer(oUserElmt, moConfig("ProjectPath") & "/xsl/email/registrationAlert.xsl", "New User", recipientEmail, fromEmail, SubjectLine, "Message Sent", "Message Failed")
                                    End If
                                    oMsg = Nothing
                                End If

                                'redirect to this page or alternative page.
                                If bRedirect Then
                                myWeb.msRedirectOnEnd = myWeb.mcOriginalURL
                            Else
                                oContentNode.InnerXml = oXfmElmt.InnerXml
                            End If
                        Else
                            oContentNode.InnerXml = oXfmElmt.InnerXml
                        End If
                    End If

                    If bLogon Then
                        'Now we want to reload as permissions have changed

                        If Not moSession Is Nothing Then
                            If Not moSession("cLogonCmd") Is Nothing Then
                                cLogonCmd = Split(moSession("cLogonCmd"), "=")(0)
                                If myWeb.mcOriginalURL.Contains(cLogonCmd & "=") Then
                                    cLogonCmd = ""
                                Else
                                    If myWeb.mcOriginalURL.Contains("=") Then
                                        cLogonCmd = "&" & moSession("cLogonCmd")
                                    Else
                                        cLogonCmd = "?" & moSession("cLogonCmd")
                                    End If
                                End If
                            End If
                        End If

                        moSession("RedirectReason") = "registration"
                        myWeb.bRedirectStarted = True ' This acts as a local suppressant allowing for the sessio to pass through to the redirected page

                        Dim redirectId As String = myWeb.moConfig("RegisterRedirectPageId")

                        If oContentNode.GetAttribute("redirectPathId") <> "" Then
                            redirectId = oContentNode.GetAttribute("redirectPathId")
                        End If

                        If redirectId <> "" Then
                            'refresh the site strucutre with new userId
                            myWeb.mnUserId = mnUserId
                            myWeb.GetStructureXML("Site")
                            Dim oElmt As XmlElement = myWeb.moPageXml.SelectSingleNode("/Page/Menu/descendant-or-self::MenuItem[@id = '" & redirectId & "']")
                            Dim redirectPath As String = myWeb.mcOriginalURL
                            If oElmt Is Nothing Then
                                myWeb.msRedirectOnEnd = redirectPath
                                bRedirect = True
                            Else
                                redirectPath = oElmt.GetAttribute("url")
                                myWeb.msRedirectOnEnd = redirectPath
                                bRedirect = False
                            End If
                        End If
                    End If

                Catch ex As Exception
                    RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "Logon", ex, ""))
                End Try
            End Sub

            Public Sub PasswordReminder(ByRef myWeb As Protean.Cms, ByRef oContentNode As XmlElement)

                Dim moConfig As System.Collections.Specialized.NameValueCollection = myWeb.moConfig
                Try
                    Dim adXfm As Object = myWeb.getAdminXform()

                    Dim oXfmElmt As XmlElement
                    If myWeb.mnUserId = 0 Then
                        Select Case LCase(moConfig("MembershipEncryption"))
                            Case "md5salt", "md5", "sha1", "sha256"
                                If myWeb.moRequest("ewCmd") = "AR-MOD" Then
                                    Dim cAccountHash As String = myWeb.moRequest("AI")
                                    'Validate to prevent SQL injection
                                    'strip out any spaces to prevent SQL injection
                                    If cAccountHash.Contains(" ") Then
                                        cAccountHash = Left(cAccountHash, InStr(cAccountHash, " "))
                                    End If
                                    If cAccountHash.Contains("%20") Then
                                        cAccountHash = Left(cAccountHash, InStr(cAccountHash, "%20"))
                                    End If
                                    Dim regex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("[\d,]")

                                    If Not regex.Match(cAccountHash).Success Then
                                        cAccountHash = ""
                                    End If

                                    If Not cAccountHash = "" Then
                                        oXfmElmt = adXfm.xFrmConfirmPassword(cAccountHash)
                                    Else
                                        oXfmElmt = adXfm.xFrmResetAccount()
                                    End If
                                Else
                                    oXfmElmt = adXfm.xFrmResetAccount()
                                End If
                            Case Else
                                oXfmElmt = adXfm.xFrmPasswordReminder()
                        End Select
                    Else
                        oXfmElmt = adXfm.xFrmConfirmPassword(myWeb.mnUserId)
                    End If

                    oContentNode.InnerXml = oXfmElmt.InnerXml

                Catch ex As Exception
                    RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "Logon", ex, ""))
                End Try
            End Sub

            Public Sub GetUserContent(ByRef myWeb As Protean.Cms, ByRef oContentNode As XmlElement)
                Dim ContentType As String = oContentNode.GetAttribute("contentType")
                Dim UserId As String = myWeb.mnUserId
                Dim WhereSql As String = " cContentSchemaName = '" & ContentType & "' and nInsertDirId = " & UserId

                Try
                    If UserId <> 0 Then
                        myWeb.mbAdminMode = True
                        myWeb.GetPageContentFromSelect(WhereSql, False,  , , , "", oContentNode, , , , True)
                        myWeb.mbAdminMode = False
                    End If

                Catch ex As Exception
                    RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "GetUserContent", ex, ""))
                End Try
            End Sub

            Public Sub GetUsersByGroup(ByRef myWeb As Protean.Cms, ByRef contentNode As XmlElement)

                Try

                    Dim cSchemaName As String = contentNode.Attributes("parentSchemaType").InnerText
                    Dim sArrDirKeys As String = contentNode.Attributes("parentIds").InnerText 'comma separated int array
                    Dim nStatus As Integer = contentNode.Attributes("parentStatus").InnerText
                    Dim nParDirId As String = contentNode.Attributes("parentParId").InnerText

                    If sArrDirKeys.Length > 0 Then

                        'make SQL statement
                        Dim strSql As New Text.StringBuilder
                        strSql.Append("CREATE TABLE #tmpTblUsers ")
                        strSql.Append("(")
                        strSql.Append("[id] INT, ")
                        strSql.Append("[Status] INT, ")
                        strSql.Append("[Username] NVARCHAR(100), ")
                        strSql.Append("[UserXml] NVARCHAR(max), ")
                        strSql.Append("[Companies] NVARCHAR(100) ")
                        strSql.Append(") ")

                        'gets all users using standard stored proc
                        strSql.Append("INSERT INTO #tmpTblUsers ")
                        strSql.Append("EXEC spGetUsers " & nParDirId.ToString & ", " & nStatus.ToString & " ")

                        'narrows scope of users
                        strSql.Append("SELECT ")
                        strSql.Append("#tmpTblUsers.[id] ")
                        strSql.Append("FROM tblDirectory AS tblGroups ")
                        strSql.Append("INNER JOIN tblDirectoryRelation ON tblGroups.nDirKey = tblDirectoryRelation.nDirParentId ")
                        strSql.Append("INNER JOIN #tmpTblUsers ON tblDirectoryRelation.nDirChildId = #tmpTblUsers.id ")
                        strSql.Append("WHERE (tblGroups.cDirSchema = '" & cSchemaName & "') ")
                        strSql.Append(" AND (tblGroups.nDirKey in (" & sArrDirKeys & ")) ")

                        'add each result to content node xml
                        Dim oDsUsers As DataSet = myWeb.moDbHelper.GetDataSet(strSql.ToString, "User", "UserGroups", )
                        Dim oDrUser As DataRow
                        For Each oDrUser In oDsUsers.Tables(0).Rows
                            contentNode.AppendChild(myWeb.GetUserXML(oDrUser("id")).Clone)
                        Next

                    End If

                Catch ex As Exception
                    returnException(myWeb.msException, mcModuleName, "GetUsersByGroup", ex, "", "", gbDebug)
                    'Return Nothing
                End Try

            End Sub

            Public Sub UserContact(ByRef myWeb As Protean.Cms, ByRef contentNode As XmlElement)

                Try

                    If myWeb.mnUserId > 0 Then

                        Dim adXfm As Object = myWeb.getAdminXform()
                        adXfm.open(myWeb.moPageXml)
                        Dim memCmd As String = myWeb.moRequest("memCmd")
                        If memCmd = "" And myWeb.moRequest("ewCmd") <> "" Then
                            memCmd = myWeb.moRequest("ewCmd")
                        End If

                        Select Case memCmd
                            Case "addContact", "editContact"
                                Dim oXfmElmt As XmlElement = adXfm.xFrmEditDirectoryContact(myWeb.moRequest("id"), myWeb.mnUserId)
                                If Not adXfm.valid Then
                                    contentNode.AppendChild(oXfmElmt)
                                Else
                                    myWeb.RefreshUserXML()
                                End If
                            Case "delContact"
                                Dim oContactElmt As XmlElement
                                For Each oContactElmt In myWeb.GetUserXML(myWeb.mnUserId).SelectNodes("descendant-or-self::Contact")
                                    Dim oId As XmlElement = oContactElmt.SelectSingleNode("nContactKey")
                                    If Not oId Is Nothing Then
                                        If oId.InnerText = myWeb.moRequest("id") Then
                                            myWeb.moDbHelper.DeleteObject(dbHelper.objectTypes.CartContact, myWeb.moRequest("id"))
                                            myWeb.RefreshUserXML()
                                        End If
                                    End If
                                Next
                        End Select
                    End If

                Catch ex As Exception
                    returnException(myWeb.msException, mcModuleName, "UserContacts", ex, "", "", gbDebug)
                    'Return Nothing
                End Try

            End Sub

            Public Sub CompanyContact(ByRef myWeb As Protean.Cms, ByRef contentNode As XmlElement)
                Dim CompanyId As Long = myWeb.moRequest("ParentDirId")
                Dim bUserValid As Boolean = True
                Try

                    ' If myWeb.mnUserId > 0 And myWeb.moPageXml.SelectSingleNode("User/Company[@id='" & CompanyId & "']") IsNot Nothing Then

                    If myWeb.mnUserId > 0 Then

                        Dim adXfm As Object = myWeb.getAdminXform()
                        adXfm.open(myWeb.moPageXml)

                        If CInt("0" & myWeb.moRequest("id")) > 0 And Not (myWeb.moPageXml.SelectSingleNode("User/Company/Contacts/Contact/nContactKey[text()='" & myWeb.moRequest("id") & "']") Is Nothing) Then
                            bUserValid = False
                        End If

                        If bUserValid Then
                            Dim memCmd As String = myWeb.moRequest("memCmd")
                            If memCmd = "" And myWeb.moRequest("ewCmd") <> "" Then
                                memCmd = myWeb.moRequest("ewCmd")
                            End If

                            Select Case memCmd
                                Case "addContact", "editContact"
                                    Dim oXfmElmt As XmlElement = adXfm.xFrmEditDirectoryContact(myWeb.moRequest("id"), CompanyId, "/xforms/directory/CompanyContact.xml")
                                    If Not adXfm.valid Then
                                        contentNode.AppendChild(oXfmElmt)
                                    Else
                                        myWeb.RefreshUserXML()
                                    End If
                                Case "delContact"
                                    Dim oContactElmt As XmlElement
                                    For Each oContactElmt In myWeb.GetUserXML(myWeb.mnUserId).SelectNodes("descendant-or-self::Contact")
                                        Dim oId As XmlElement = oContactElmt.SelectSingleNode("nContactKey")
                                        If Not oId Is Nothing Then
                                            If oId.InnerText = myWeb.moRequest("id") Then
                                                myWeb.moDbHelper.DeleteObject(dbHelper.objectTypes.CartContact, myWeb.moRequest("id"))
                                                myWeb.RefreshUserXML()
                                            End If
                                        End If
                                    Next
                            End Select
                        End If

                    End If

                Catch ex As Exception
                    returnException(myWeb.msException, mcModuleName, "CompanyContact", ex, "", "", gbDebug)
                    'Return Nothing
                End Try

            End Sub

            Public Sub AddUserToGroup(ByRef myWeb As Protean.Cms, ByRef contentNode As XmlElement)
                Dim groupNode As XmlElement
                Try

                    If myWeb.mnUserId > 0 And Not (contentNode.SelectSingleNode("ancestor::Order") Is Nothing) Then

                        For Each groupNode In contentNode.SelectNodes("descendant-or-self::UserGroups/Group")
                            Dim groupId As String = groupNode.GetAttribute("id")
                            If IsNumeric(groupId) Then
                                'Dim cUserEmail As String = myWeb.moDbHelper.getNameByKey(dbHelper.objectTypes.Directory, myWeb.mnUserId)
                                'Dim cGroupName As String = myWeb.moDbHelper.getNameByKey(dbHelper.objectTypes.Directory, CLng(groupId))

                                myWeb.moDbHelper.maintainDirectoryRelation(CLng(groupId), myWeb.mnUserId, False)
                            End If
                        Next

                    End If

                Catch ex As Exception
                    returnException(myWeb.msException, mcModuleName, "AddUserToGroup", ex, "", "", gbDebug)
                    'Return Nothing
                End Try

            End Sub

            Public Sub JobApplication(ByRef myWeb As Protean.Cms, ByRef oContentNode As XmlElement)

                Dim cProcessInfo As String
                Dim moConfig As System.Collections.Specialized.NameValueCollection = myWeb.moConfig
                Dim oElmt As XmlElement
                Dim JobId As Long = CLng("0" & myWeb.moRequest("JobId"))
                Dim FormId As Long = CLng("0" & myWeb.moRequest("FormId"))
                Try
                    If myWeb.mnUserId = 0 Then
                        Register(myWeb, oContentNode)

                        Dim logonContentNode As XmlElement = myWeb.moPageXml.CreateElement("Content")
                        oContentNode.ParentNode.AppendChild(logonContentNode)

                        Logon(myWeb, logonContentNode)

                    Else
                        If myWeb.moRequest("FormId") = "" Then
                            'List User Applications
                            Dim strSql As New Text.StringBuilder
                            strSql.Append("SELECT * FROM [tblEmailActivityLog] eal ")
                            strSql.Append("INNER JOIN tblActivityLog al on al.nOtherId = eal.nEmailActivityKey ")
                            strSql.Append("where al.nUserDirId = " & myWeb.mnUserId)
                            Dim oDsJobs As DataSet = myWeb.moDbHelper.GetDataSet(strSql.ToString, "Application", "JobApplications", )
                            oContentNode.InnerXml = Replace(oDsJobs.GetXml, "xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""", "")
                            Dim oElmt2 As XmlElement
                            Dim sContent As String
                            For Each oElmt2 In oContentNode.SelectNodes("descendant-or-self::cActivityXml | descendant-or-self::cActivityDetail")
                                sContent = oElmt2.InnerText
                                If sContent <> "" Then
                                    Try
                                        oElmt2.InnerXml = sContent
                                    Catch
                                        oElmt2.InnerXml = Protean.tidyXhtmlFrag(sContent)
                                    End Try
                                End If
                            Next

                        ElseIf oContentNode.ParentNode.Name = "ContentDetail" Then
                            'remove application forms not required
                            For Each oElmt In oContentNode.SelectNodes("Content[@id!='" & myWeb.moRequest("FormId") & "']")
                                oElmt.ParentNode.RemoveChild(oElmt)
                            Next

                            For Each oElmt In oContentNode.SelectNodes("Content[@id='" & myWeb.moRequest("FormId") & "']")

                                'Form Handling
                                Dim oXform As Protean.xForm = myWeb.getXform()

                                oXform.moPageXML = myWeb.moPageXml
                                oXform.load(oElmt, True)

                                If myWeb.moRequest("stageButton") = "" And myWeb.moRequest("stage") <> "" Then
                                    Dim passportNode2 As XmlElement = oXform.Instance.SelectSingleNode("descendant-or-self::SkillsPassport")
                                    passportNode2.SetAttribute("stage", myWeb.moRequest("stage"))
                                    myWeb.moSession("tempInstance") = oXform.Instance
                                End If

                                Dim strSql As New Text.StringBuilder
                                strSql.Append("SELECT eal.nEmailActivityKey FROM [tblEmailActivityLog] eal ")
                                strSql.Append("INNER JOIN tblActivityLog al on al.nOtherId = eal.nEmailActivityKey ")
                                strSql.Append("where al.nUserDirId = " & myWeb.mnUserId & " and al.nArtId = " & JobId)
                                Dim EmailActivityId As Long = CLng("0" & myWeb.moDbHelper.GetDataValue(strSql.ToString))
                                If EmailActivityId > 0 Then
                                    'load in a saved instance
                                    Dim strSql2 As New Text.StringBuilder
                                    strSql2.Append("SELECT cActivityXml FROM [tblEmailActivityLog] eal ")
                                    strSql2.Append("INNER JOIN tblActivityLog al on al.nOtherId = eal.nEmailActivityKey ")
                                    strSql2.Append("where al.nUserDirId = " & myWeb.mnUserId & " and al.nArtId = " & JobId)

                                    Dim loadedInstance As String = myWeb.moDbHelper.GetDataValue(strSql2.ToString)
                                    If loadedInstance <> "" And myWeb.moSession("tempInstance") Is Nothing Then
                                        Dim oLoadedInstance As XmlElement = myWeb.moPageXml.CreateElement("instance")
                                        oLoadedInstance.InnerXml = loadedInstance
                                        'tidy up the stage editor

                                        oXform.Instance = oLoadedInstance.FirstChild
                                    End If
                                Else
                                    'set the job title
                                    Dim JobTitleNode As XmlElement = oXform.Instance.SelectSingleNode("descendant-or-self::SkillsPassport/LearnerInfo/Headline/Type/Label")
                                    JobTitleNode.InnerText = myWeb.moRequest("JobApply")
                                    Dim JobCodeNode As XmlElement = oXform.Instance.SelectSingleNode("descendant-or-self::SkillsPassport/LearnerInfo/Headline/Type/Code")
                                    JobCodeNode.InnerText = myWeb.moRequest("JobId")
                                End If

                                If oXform.isSubmitted Then

                                    oXform.updateInstanceFromRequest()

                                    'tidy up the stage editor
                                    If myWeb.moRequest("stageButton") = "" Then
                                        Dim passportNode As XmlElement = oXform.Instance.SelectSingleNode("descendant-or-self::SkillsPassport")
                                        passportNode.SetAttribute("stage", myWeb.moRequest("stage"))
                                    End If

                                    ' save instace & progress
                                    If EmailActivityId > 0 Then
                                        Dim strSql3 As New Text.StringBuilder
                                        strSql3.Append("update tblEmailActivityLog set cActivityXml = '" & SqlFmt(oXform.Instance.OuterXml) & "'")
                                        strSql3.Append("where nEmailActivityKey = " & EmailActivityId)
                                        myWeb.moDbHelper.ExeProcessSql(strSql3.ToString)
                                    Else
                                        EmailActivityId = myWeb.moDbHelper.emailActivity(myWeb.mnUserId, , , , oXform.Instance.OuterXml)
                                        myWeb.moDbHelper.logActivity(dbHelper.ActivityType.JobApplication, myWeb.mnUserId, 0, JobId, EmailActivityId, "")
                                    End If

                                    If myWeb.moRequest("SaveExit") <> "" Then

                                        myWeb.msRedirectOnEnd = myWeb.mcPagePath

                                    End If

                                    If myWeb.moRequest("stageButton") = "Validate" Then

                                        'We validate the form

                                        Dim oSkillsPassport As XmlElement = oXform.Instance.SelectSingleNode("emailer/oBodyXML/SkillsPassport")
                                        oSkillsPassport.SetAttribute("stage", "Validate")
                                        oXform.validate()

                                        If oXform.valid Then
                                            Dim sMessage As String

                                            Dim oMsg As Protean.Messaging = New Protean.Messaging(myWeb.msException)

                                            sMessage = oMsg.emailer(oXform.Instance.SelectSingleNode("emailer/oBodyXML"),
                                                                    oXform.Instance.SelectSingleNode("emailer/xsltPath").InnerText,
                                                                    oXform.Instance.SelectSingleNode("emailer/fromName").InnerText,
                                                                    oXform.Instance.SelectSingleNode("emailer/fromEmail").InnerText,
                                                                    oXform.Instance.SelectSingleNode("emailer/recipientEmail").InnerText,
                                                                    oXform.Instance.SelectSingleNode("emailer/SubjectLine").InnerText, , , ,
                                                                    oXform.Instance.SelectSingleNode("emailer/ccRecipient").InnerText,
                                                                    oXform.Instance.SelectSingleNode("emailer/bccRecipient").InnerText,
                                                                    "")
                                            'Return sMessage
                                            Dim oEmailer As XmlElement = oXform.Instance.SelectSingleNode("emailer")
                                            oEmailer.SetAttribute("SubmitMessage", sMessage)

                                            oSkillsPassport.SetAttribute("stage", "Complete")

                                        End If

                                        Dim strSql3 As New Text.StringBuilder
                                        strSql3.Append("update tblEmailActivityLog set cActivityXml = '" & SqlFmt(oXform.Instance.OuterXml) & "'")
                                        strSql3.Append("where nEmailActivityKey = " & EmailActivityId)
                                        myWeb.moDbHelper.ExeProcessSql(strSql3.ToString)

                                    End If
                                End If

                                oXform.addValues()

                                oElmt.InnerXml = oXform.moXformElmt.InnerXml
                                oXform = Nothing

                            Next
                            'Load Application Form
                        Else
                            cProcessInfo = "only run on content detail"
                            'do nothing
                        End If
                    End If

                    'Dim adXfm As Object = myWeb.getAdminXform()
                    'Dim oXfmElmt As XmlElement

                    'oContentNode.InnerXml = oXfmElmt.InnerXml

                Catch ex As Exception
                    RaiseEvent OnError(Me, New Protean.Tools.Errors.ErrorEventArgs(mcModuleName, "Logon", ex, ""))
                End Try
            End Sub

        End Class

#End Region

        Protected Overrides Sub Finalize()
            MyBase.Finalize()
        End Sub
    End Class
End Class


text:
package com.palantir.gradle.dist;

public final class Versions {

    public static final String GRADLE_CONSISTENT_VERSIONS = "1.27.0";

    private Versions() {}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
S-Index
</TITLE>

<META NAME="date" CONTENT="2014-05-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I K L M N O P R S T U

S

saveSettings() -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

Add or update application settings

SDK_VERSION -
Static variable in class ca.cumulonimbus.pressurenetsdk.CbConfiguration

sendCbAccount(CbAccount) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

Send a new account to the server

sendCbCurrentCondition(CbCurrentCondition) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

Send the current condition to the server

sendCbObservation(CbObservation) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

Send the observation to the server

sendSingleObs() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

sensorId -
Variable in class ca.cumulonimbus.pressurenetsdk.CbService.CbSensorStreamer

SERVER_URL -
Static variable in class ca.cumulonimbus.pressurenetsdk.CbConfiguration

service -
Variable in class ca.cumulonimbus.pressurenetsdk.CbService

setAlarm(Context, long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbAlarm

setAnimateGroupNumber(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbWeather

setApiKey(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setApiName(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setAppID(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setCallType(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setCallURL(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setClientKey(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setCloud_type(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setCollectingData(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setConditionResults(ArrayList<CbCurrentCondition>) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setConditionsAllTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbContributions

setConditionsLastDay(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbContributions

setConditionsLastWeek(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbContributions

setDataCollectionFrequency(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setDataCollector(CbService.CbDataCollector) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

setEmail(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbAccount

setEndTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setEndTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStatsAPICall

setFog_thickness(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setFormat(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setGeneral_condition(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setGeohash(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setGlobal(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setjDate(Date) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setLat(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setLimit(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setLocation(Location) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setLocation(Location) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setLocationManager(CbLocationManager) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

setLogDuration(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStatsAPICall

setLon(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setMax(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setMaxLat(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setMaxLatitude(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStatsAPICall

setMaxLon(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setMaxLongitude(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStatsAPICall

setMean(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setMedian(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setMin(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setMinDistance(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbLocationManager

setMinLat(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setMinLatitude(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStatsAPICall

setMinLon(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setMinLongitude(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStatsAPICall

setMinTime(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbLocationManager

setObservationResults(ArrayList<CbObservation>) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setObservationType(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setObservationUnit(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setObservationValue(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setOnlyWhenCharging(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setPackageName(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbRegisteredApp

setPrecipitation_amount(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setPrecipitation_type(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setPrecipitation_unit(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setPressureAllTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbContributions

setPressureLast24h(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbContributions

setPressureLast7d(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbContributions

setRecentObservations(ArrayList<CbObservation>) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService.CbDataCollector

setRegistrationTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbRegisteredApp

setRepeating(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbAlarm

setSamples(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setSendNotifications(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setSensor(Sensor) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setServerURL(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setSettings(CbSettingsHandler, CbLocationManager, Messenger, boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbDataSender

setShareLevel(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setSharing(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setSharing_policy(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setSharingData(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setSinceLastCall(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setStartTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbApiCall

setStartTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStatsAPICall

setStdDev(double) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setThunderstorm_intensity(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setTime(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setTimeRegistered(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbAccount

setTimeStamp(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setTimeZoneOffset(long) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

SETTINGS_TABLE -
Static variable in class ca.cumulonimbus.pressurenetsdk.CbDb

setTrend(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setTzoffset(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setUpFiles() -
Method in class ca.cumulonimbus.pressurenetsdk.CbDataSender

Prepare to write a log to SD card.

setUpFiles() -
Method in class ca.cumulonimbus.pressurenetsdk.CbLocationManager

Prepare to write a log to SD card.

setUpFiles() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

setUseGPS(boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbSettingsHandler

setUser_comment(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setUser_id(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

setUser_id(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setUserID(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbAccount

setUsers(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbStats

setVersionNumber(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbObservation

setWindy(String) -
Method in class ca.cumulonimbus.pressurenetsdk.CbCurrentCondition

slopeOfBestFit(List<CbObservation>) -
Static method in class ca.cumulonimbus.pressurenetsdk.CbScience

Calculate the slope of a line of best fit

STAGING_URL -
Static variable in class ca.cumulonimbus.pressurenetsdk.CbConfiguration

startCollectingData() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService.CbDataCollector

Start collecting sensor data.

startGettingLocations() -
Method in class ca.cumulonimbus.pressurenetsdk.CbLocationManager

Get the user's location from the location service

startSendingData() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService.CbSensorStreamer

Start collecting sensor data.

startSensorStream(int, Messenger) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

Start live sensor streaming from the service
 to the app.

startSubmit() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

Start the periodic data collection.

startWithDatabase() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

startWithIntent(Intent, boolean) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

stopAutoSubmit() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

Stop all listeners, active sensors, etc, and shut down.

stopCollectingData() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService.CbDataCollector

Stop collecting sensor data

stopGettingLocations() -
Method in class ca.cumulonimbus.pressurenetsdk.CbLocationManager

Stop all location listeners

stopSendingData() -
Method in class ca.cumulonimbus.pressurenetsdk.CbService.CbSensorStreamer

Stop collecting sensor data

stopSensorStream(int) -
Method in class ca.cumulonimbus.pressurenetsdk.CbService

Stop live sensor streaming.

stringTimeToLongHack(String) -
Static method in class ca.cumulonimbus.pressurenetsdk.CbService

Convert time ago text to ms.

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I K L M N O P R S T U


text:
package org.lightadmin.boot.domain;

/**
 * Created by spooky on 2/18/16.
 */
public enum Gender {
    none,
    male,
    female
}


text:
import { CommandableLambdaFunction } from 'pip-services3-aws-node';
export declare class QuotesLambdaFunction extends CommandableLambdaFunction {
    constructor();
}
export declare const handler: (event: any, context: any) => void;


text:
    ${i18n("signUpAlreadyHasAccount")}

    ${i18n("signUpAlreadyHasAccountTextPrefix")}

        ${i18n("signInLinkTitle")}

    ${i18n("signUpAlreadyHasAccountTextPostfix")}


text:
/*
 * Dht11.cpp
 *
 * Version 0.5
 *
 * DHT11 Temperature and humidity sensor library for Arduino.
 *
 * See http://playground.arduino.cc/main/DHT11Lib
 *
 * License:   GPL v3 (http://www.gnu.org/licenses/gpl.html)
 * Datasheet: http://www.micro4you.com/files/sensor/DHT11.pdf
 *
 * Modification History:
 *   - George Hadjikyriacou                     - Version 0.1 (??)
 *   - SimKard                                  - Version 0.2 (24/11/2010)
 *   - Rob Tillaart                             - Version 0.3 (28/03/2011)
 *       * Added comments
 *       * Removed all non-DHT11 specific code
 *       * Added References
 *   - Rob Tillaart                             - Version 0.4 (17/03/2012)
 *       * Added Arduino 1.0 support
 *   - Rob Tillaart                             - Version 0.4.1 (19/05/2012)
 *       * Added error codes
 *   - Andy Dalton                              - Version 0.5 (13/09/2013)
 *       * Replaced magic numbers with named constants
 *       * Factored out repeated code into a helper method.
 *       * Made pin a parameter to the constructor instead of a parameter
 *         to read()
 *       * Changed the error codes to an enumeration
 *       * Update the temp/humidity only if the checksum is correct
 *       * Added more comments
 */
#include "Dht11.h"

#define BITS_IN(object) (8 * sizeof((object)))

// The version of this code
const char* const Dht11::VERSION = "0.5";

// Various named constants.
enum {
    /*
     * Time required to signal the DHT11 to switch from low power mode to
     * running mode.  18 ms is the minimal, add a few extra ms to be safe.
     */
    START_SIGNAL_WAIT = 20,

    /*
     * Once the start signal has been sent, we wait for a response.  The doc
     * says this should take 20-40 us, we wait 5 ms to be safe.
     */
    RESPONSE_WAIT =  5,

    /*
     * The time threshold between a 0 bit and a 1 bit in the response.  Times
     * greater than this (in ms) will be considered a 1; otherwise they'll be
     * considered a 0.
     */
    ONE_THRESHOLD = 40,

    /*
     * The number of bytes we expect from the sensor.  This consists of one
     * byte for the integral part of the humidity, one byte for the fractional
     * part of the humidity, one byte for the integral part of the temperature,
     * one byte for the fractional part of the temperature, and one byte for
     * a checksum.  The DHT11 doesn't capture the fractional parts of the
     * temperature and humidity, but it doesn't transmit data during those
     * times.
     */
    RESPONSE_SIZE =  5,

    /*
     * The number of bits in a bytes.
     */
    BITS_PER_BYTE =  8,

    /*
     * The 0-base most significant bit in a byte.
     */
    BYTE_MS_BIT =  7,

    /*
     * The index in the response where the humidity reading is stored.
     */
    HUMIDITY_INDEX =  0,

    /*
     * The index in the response where the temperature is stored.
     */
    TEMPERATURE_INDEX =  2,

    /*
     * The index in the response where the checksum is stored.
     */
    CHECKSUM_INDEX =  4,
};

Dht11::ReadStatus Dht11::read() {
    uint8_t    buffer[RESPONSE_SIZE] = { 0 };
    uint8_t    bitIndex              = BYTE_MS_BIT;
    ReadStatus status                = OK;

    // Request sample
    pinMode(this->pin, OUTPUT);
    digitalWrite(this->pin, LOW);
    delay(START_SIGNAL_WAIT);

    // Wait for response
    digitalWrite(this->pin, HIGH);
    delayMicroseconds(RESPONSE_WAIT);
    pinMode(this->pin, INPUT);

    // Acknowledge or timeout
    // Response signal should first be low for 80us...
    if ((status = this->waitForPinChange(LOW)) != OK) {
        goto done;
    }

    // ... then be high for 80us ...
    if ((status = this->waitForPinChange(HIGH)) != OK) {
        goto done;
    }

    /*
     * ... then provide 5 bytes of data that include the integral part of the
     * humidity, the fractional part of the humidity, the integral part of the
     * temperature, the fractional part of the temperature, and a checksum
     * that is the sum of the integral parts of humidity and temperature.
     */
    for (size_t i = 0; i < BITS_IN(buffer); i++) {
        if ((status = this->waitForPinChange(LOW)) != OK) {
            goto done;
        }

        unsigned long highStart = micros();

        if ((status = this->waitForPinChange(HIGH)) != OK) {
            goto done;
        }

        // 26-28 us = 0, 50 us = 1.  40 us is a good threshold between 0 and 1
        if ((micros() - highStart) > ONE_THRESHOLD) {
            buffer[i / BITS_PER_BYTE] |= (1 << bitIndex);
        }

        // Decrement or reset bitIndex
        bitIndex = (bitIndex > 0) ? bitIndex - 1 : BYTE_MS_BIT;
    }

    // Check the checksum.  Only if it's good, record the new values.
    if (buffer[CHECKSUM_INDEX] == (  buffer[HUMIDITY_INDEX]
                                   + buffer[TEMPERATURE_INDEX])) {
        // buffer[1] and buffer[3] should be the fractional parts of the
        // humidity and temperature, respectively, but the DHT11 doesn't
        // provide those values, so we omit them here.
        this->humidity    = buffer[HUMIDITY_INDEX];
        this->temperature = buffer[TEMPERATURE_INDEX];
    } else {
        status = ERROR_CHECKSUM;
    }

done:
    return status;
}


text:
package engagebdr

import (
	"encoding/json"
	"net/http"

	"github.com/prebid/openrtb/v17/openrtb2"
	"github.com/prebid/prebid-server/config"
	"github.com/prebid/prebid-server/openrtb_ext"

	"fmt"

	"github.com/prebid/prebid-server/adapters"
	"github.com/prebid/prebid-server/errortypes"
)

type EngageBDRAdapter struct {
	URI string
}

func (adapter *EngageBDRAdapter) MakeRequests(request *openrtb2.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {

	errors := make([]error, 0, len(request.Imp))

	if request.Imp == nil || len(request.Imp) == 0 {
		errors = append(errors, &errortypes.BadInput{
			Message: fmt.Sprintf("Invalid BidRequest. No valid imp."),
		})
		return nil, errors
	}

	// EngageBDR uses different sspid parameters for banner and video.
	sspidImps := make(map[string][]openrtb2.Imp)
	for _, imp := range request.Imp {

		if imp.Audio != nil {
			errors = append(errors, &errortypes.BadInput{
				Message: fmt.Sprintf("Ignoring imp id=%s, invalid MediaType. EngageBDR only supports Banner, Video and Native.", imp.ID),
			})
			continue
		}

		var bidderExt adapters.ExtImpBidder
		if err := json.Unmarshal(imp.Ext, &bidderExt); err != nil {
			errors = append(errors, &errortypes.BadInput{
				Message: fmt.Sprintf("Ignoring imp id=%s, error while decoding extImpBidder, err: %s.", imp.ID, err),
			})
			continue
		}
		impExt := openrtb_ext.ExtImpEngageBDR{}
		err := json.Unmarshal(bidderExt.Bidder, &impExt)
		if err != nil {
			errors = append(errors, &errortypes.BadInput{
				Message: fmt.Sprintf("Ignoring imp id=%s, error while decoding impExt, err: %s.", imp.ID, err),
			})
			continue
		}
		if impExt.Sspid == "" {
			errors = append(errors, &errortypes.BadInput{
				Message: fmt.Sprintf("Ignoring imp id=%s, no sspid present.", imp.ID),
			})
			continue
		}
		sspidImps[impExt.Sspid] = append(sspidImps[impExt.Sspid], imp)
	}

	var adapterRequests []*adapters.RequestData

	headers := http.Header{}
	headers.Add("Content-Type", "application/json;charset=utf-8")

	for sspid, imps := range sspidImps {
		if len(imps) > 0 {
			// Make a copy as we don't want to change the original request
			reqCopy := *request
			reqCopy.Imp = imps
			reqJSON, err := json.Marshal(reqCopy)
			if err != nil {
				errors = append(errors, err)
				return nil, errors
			}
			adapterReq := adapters.RequestData{
				Method:  "POST",
				Uri:     adapter.URI + "?zoneid=" + sspid,
				Body:    reqJSON,
				Headers: headers,
			}
			adapterRequests = append(adapterRequests, &adapterReq)
		}
	}

	return adapterRequests, errors
}

func (adapter *EngageBDRAdapter) MakeBids(internalRequest *openrtb2.BidRequest, externalRequest *adapters.RequestData, response *adapters.ResponseData) (*adapters.BidderResponse, []error) {
	if response.StatusCode == http.StatusNoContent {
		return nil, nil
	}

	if response.StatusCode == http.StatusBadRequest {
		return nil, []error{&errortypes.BadInput{
			Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
		}}
	}

	if response.StatusCode != http.StatusOK {
		return nil, []error{&errortypes.BadServerResponse{
			Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
		}}
	}

	var bidResp openrtb2.BidResponse
	if err := json.Unmarshal(response.Body, &bidResp); err != nil {
		return nil, []error{err}
	}

	bidResponse := adapters.NewBidderResponseWithBidsCapacity(5)

	for _, sb := range bidResp.SeatBid {
		for i := range sb.Bid {
			bidResponse.Bids = append(bidResponse.Bids, &adapters.TypedBid{
				Bid:     &sb.Bid[i],
				BidType: getMediaTypeForImp(sb.Bid[i].ImpID, internalRequest.Imp),
			})
		}
	}
	return bidResponse, nil
}

func getMediaTypeForImp(impId string, imps []openrtb2.Imp) openrtb_ext.BidType {
	mediaType := openrtb_ext.BidTypeBanner
	for _, imp := range imps {
		if imp.ID == impId {
			if imp.Video != nil {
				mediaType = openrtb_ext.BidTypeVideo
			} else if imp.Native != nil {
				mediaType = openrtb_ext.BidTypeNative
			}
			return mediaType
		}
	}
	return mediaType
}

// Builder builds a new instance of the EngageBDR adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter, server config.Server) (adapters.Bidder, error) {
	bidder := &EngageBDRAdapter{
		URI: config.Endpoint,
	}
	return bidder, nil
}


text:
#region License

#endregion

using System.Runtime.Serialization;

namespace Quartz
{
	/// <summary>
	/// An exception that is thrown to indicate that cancellation failed.
	/// </summary>
	/// <author>James House</author>
    /// <author>Marko Lahma (.NET)</author>
    [Serializable]
    public sealed class UnableToInterruptJobException : SchedulerException
	{
		/// <summary>
		/// Create a <see cref="UnableToInterruptJobException" /> with the given message.
		/// </summary>
		public UnableToInterruptJobException(string message) : base(message)
		{
		}

		/// <summary>
		/// Create a <see cref="UnableToInterruptJobException" /> with the given cause.
		/// </summary>
		public UnableToInterruptJobException(Exception innerException) : base(innerException)
		{
		}

        /// <summary>
        /// Initializes a new instance of the <see cref="UnableToInterruptJobException"/> class.
        /// </summary>
        /// <param name="info">The <see cref="T:SerializationInfo"></see> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"></see> that contains contextual information about the source or destination.</param>
        /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"></see> is zero (0). </exception>
        /// <exception cref="T:System.ArgumentNullException">The info parameter is null. </exception>
        public UnableToInterruptJobException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
<!--
  ~ Copyright (c) 2018 ThanksMister LLC
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software distributed
  ~ under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
            android:id="@+id/mainView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

        <fragment
                android:name="com.thanksmister.iot.mqtt.alarmpanel.ui.fragments.InformationFragment"
                android:id="@+id/informationContainer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:layout="@layout/fragment_information"/>

        <fragment
                android:name="com.thanksmister.iot.mqtt.alarmpanel.ui.fragments.ControlsFragment"

                android:id="@+id/controlContainer"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                tools:layout="@layout/fragment_controls"/>

        <LinearLayout
                android:id="@+id/settingsContainer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="end"
                android:paddingBottom="2dp"
                android:paddingStart="16dp"
                android:paddingEnd="16dp"
                android:orientation="horizontal">

            <ImageButton
                android:id="@+id/platformButton"
                style="@style/BorderlessButtonStyle"
                android:padding="4dp"
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:tint="@color/dark_gray"
                android:scaleType="fitCenter"
                android:src="@drawable/ic_home_black"
                tools:ignore="ContentDescription"/>

            <android.support.v4.widget.Space
                android:layout_width="12dp"
                android:layout_height="24dp"/>

            <ImageButton
                    android:id="@+id/buttonSleep"
                    style="@style/BorderlessButtonStyle"
                android:padding="4dp"
                android:layout_width="36dp"
                android:layout_height="36dp"
                    android:tint="@color/dark_gray"
                    android:scaleType="fitCenter"
                    android:src="@drawable/ic_sleep_24dp"
                    tools:ignore="ContentDescription"/>

            <android.support.v4.widget.Space
                    android:layout_width="12dp"
                    android:layout_height="24dp"/>

            <ImageButton
                    android:id="@+id/buttonSettings"
                    style="@style/BorderlessButtonStyle"
                    android:padding="4dp"
                    android:layout_width="36dp"
                    android:layout_height="36dp"
                    android:tint="@color/dark_gray"
                    android:scaleType="fitCenter"
                    android:src="@drawable/ic_settings_black_24dp"
                    tools:ignore="ContentDescription"/>

            <android.support.v4.widget.Space
                    android:layout_width="12dp"
                    android:layout_height="24dp"/>

            <ImageButton
                    android:id="@+id/buttonLogs"
                    style="@style/BorderlessButtonStyle"
                    android:padding="4dp"
                    android:layout_width="36dp"
                    android:layout_height="36dp"
                    android:tint="@color/dark_gray"
                    android:scaleType="fitCenter"
                    android:src="@drawable/ic_log_list_black_24dp"
                    tools:ignore="ContentDescription"/>

        </LinearLayout>

    </LinearLayout>

    <FrameLayout
            android:id="@+id/triggeredView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/red"
            tools:visibility="gone"
            android:visibility="gone">

        <include
                android:id="@+id/alarmTriggeredView"
                layout="@layout/dialog_alarm_triggered_code"/>

    </FrameLayout>

</FrameLayout>


text:
<?xml version="1.0"?>
<package>
  <name>waypoint_painter</name>
  <version>0.0.1</version>
  <description>The waypoint_painter example package</description>

  <maintainer email="gareth.roberts@manchester.ac.uk">Gareth Roberts</maintainer>

  <license>MIT</license>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>mavros</build_depend>
  <run_depend>mavros</run_depend>
</package>


text:
module SmartAnswer
  class OverseasPassportsFlow < Flow
    def define
      name 'overseas-passports'
      status :published
      satisfies_need "100131"

      data_query = Calculators::PassportAndEmbassyDataQuery.new

      exclude_countries = %w(holy-see british-antarctic-territory)

      # Q1
      country_select :which_country_are_you_in?, exclude_countries: exclude_countries do
        save_input_as :current_location

        calculate :location do
          loc = WorldLocation.find(current_location)
          if Calculators::PassportAndEmbassyDataQuery::ALT_EMBASSIES.has_key?(current_location)
            loc = WorldLocation.find(Calculators::PassportAndEmbassyDataQuery::ALT_EMBASSIES[current_location])
          end
          raise InvalidResponse unless loc
          loc
        end

        next_node_if(:cannot_apply, data_query.ineligible_country?)
        next_node_if(:which_opt?, responded_with('the-occupied-palestinian-territories'))
        next_node_if(:apply_in_neighbouring_country, data_query.apply_in_neighbouring_countries?)
        next_node(:renewing_replacing_applying?)
      end

      # Q1a
      multiple_choice :which_opt? do
        option :gaza
        option :"jerusalem-or-westbank"

        save_input_as :current_location
        next_node :renewing_replacing_applying?
      end

      # Q2
      multiple_choice :renewing_replacing_applying? do
        option :renewing_new
        option :renewing_old
        option :applying
        option :replacing

        save_input_as :application_action

        precalculate :organisation do
          location.fco_organisation
        end

        calculate :overseas_passports_embassies do
          if organisation
            organisation.offices_with_service 'Overseas Passports Service'
          else
            []
          end
        end

        calculate :general_action do |response|
          response =~ /^renewing_/ ? 'renewing' : response
        end

        calculate :passport_data do
          data_query.find_passport_data(current_location)
        end
        calculate :application_type do
          passport_data['type']
        end
        calculate :is_ips_application do
          data_query.ips_application?.call(self, nil)
        end
        calculate :ips_number do
          application_type.split("_")[2] if is_ips_application
        end

        calculate :application_form do
          passport_data['app_form']
        end

        calculate :supporting_documents do
          passport_data['group']
        end

        calculate :application_address do
          passport_data['address']
        end

        calculate :ips_docs_number do
          supporting_documents.split("_")[3] if is_ips_application
        end

        calculate :ips_result_type do
          passport_data['online_application'] ? :ips_application_result_online : :ips_application_result
        end

        data_query.passport_costs.each do |k, v|
          calculate "costs_#{k}".to_sym do
            v
          end
        end

        calculate :waiting_time do
          passport_data[application_action]
        end

        calculate :optimistic_processing_time do
          passport_data['optimistic_processing_time?']
        end

        next_node :child_or_adult_passport?
      end

      # Q3
      multiple_choice :child_or_adult_passport? do
        option :adult
        option :child

        save_input_as :child_or_adult

        on_condition(data_query.ips_application?) do
          next_node_if(:country_of_birth?, variable_matches(:application_action, %w(applying renewing_old)))
          next_node_if(:ips_application_result_online, variable_matches(:ips_result_type, :ips_application_result_online))
          next_node(:ips_application_result)
        end
      end

      # Q4
      country_select :country_of_birth?, include_uk: true, exclude_countries: exclude_countries do
        save_input_as :birth_location

        calculate :application_group do |response|
          data_query.find_passport_data(response)['group']
        end

        calculate :supporting_documents do |response|
          response == 'united-kingdom' ? supporting_documents : application_group
        end

        calculate :ips_docs_number do
          supporting_documents.split("_")[3]
        end

        on_condition(data_query.ips_application?) do
          next_node_if(:ips_application_result_online, variable_matches(:ips_result_type, :ips_application_result_online))
          next_node(:ips_application_result)
        end
      end

      ## Online IPS Application Result
      outcome :ips_application_result_online do
        precalculate :birth_location do
          birth_location
        end
      end

      ## IPS Application Result
      outcome :ips_application_result do
        precalculate :data_query do
          data_query
        end

        precalculate :birth_location do
          birth_location
        end
      end

      ## No-op outcome.
      outcome :cannot_apply

      outcome :apply_in_neighbouring_country do
        precalculate :title_output do
          location.name
        end
      end
    end
  end
end