Vb.net logout link invokemember - hyperlink

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
WebBrowser1.Document.GetElementById("xn_logout").InvokeMember("click")
End Sub
Not able to click logout link from a website what am i doing wrong here.

'WebBrowser1.Document.GetElementById("xn_username").InvokeMember("click")
Dim HtmlElementcoll As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a")
For Each elem As HtmlElement In HtmlElementcoll
' Check the attributtes you want
If elem.GetAttribute("dojotype") = "PostLink" Then
'Check even the text if you want
' If elem.InnerText = "Sign In" Then
'Invoke your event
elem.InvokeMember("click")
'End If
End If
Next
End Sub
According to my research that is what i got..

Related

How to reload code in Active Admin Custom Batch Actions?

I use active admin in a Rails app with custom batch actions.
The batch actions are created from the last 5 records from the database. Please find attached the code below.
However when a new record (Event) is created the batch actions do not refresh. I would like to know how to force a refresh? Is there a function I can call to make the batch actions refresh from new records? Thanks
ActiveAdmin.register TimeLineMessage do
menu
menu label: 'Rundown page'
Event.order("created_at DESC").limit(5).reload.each do |event|
batch_action ("Move to " + event.name.to_s).to_sym do |ids|
TimeLineMessage.find(ids).each do |tlm|
tlm.event_id = event.id
tlm.save
end
redirect_to collection_path, alert: "The content tiles have been moved to "+ event.name.to_s + " event "
end
end
Ref: http://activeadmin.info/docs/9-batch-actions.html
The way you want to go can't work, because of the fact that the code is only executed one time at the boot of Rails/ActiveAdmin.
But there is a other way that you can go:
batch_action :attach_to_event, form: {
event_id: -> { Event.order("created_at DESC").limit(5).pluck(:id, :name) }
} do |ids, inputs|
event = Event.find(inputs[:event_id])
TimeLineMessage.find(ids).each do |tlm|
tlm.event_id = event.id
tlm.save
end
redirect_to collection_path, alert: "The content tiles have been moved to "+ event.name.to_s + " event "
end
The code isn't tested by me, but the idea should work.
The approach that worked for me instead of trying to force a refresh/attach_to_event is to re-calculate on each load, pass a lambda as the value of form.
For details see : ActiveAdmin Batch Action Dynamic Form

How can I declare a global variable in Ruby on Rails?

How can I declare a global variable in Ruby on Rails?
My sample code:
in my controller#application.rb:
def user_clicked()
#current_userid = params[:user_id]
end
in my layout#application.html.haml
I have sidebar with this link:
= link_to "John", user_clicked_path(:user_id => 1)
= link_to "Doe", user_clicked_path(:user_id => 2)
= link_to "View clicked user", view_user_path
in my views#view_user.html.haml:
%h2 #current_userid
I want to declare a global variable that can modify my controller and use it anywhere, like controller, views, and etc. The above is only a sample scenario. If I click the John or Doe link, it will send a user_id to the controller and when I click the "View clicked user" link, it will display the last clicked link. It is either John=1 or Doe=2.
Of course if I click the "View clicked user" link first, it will display nil.
In Ruby global variables are declared by prefixing the identifier with $
$foo = 'bar'
Which you rarely see used for a number of reasons. And it's not really what you are looking for.
In Ruby instance variables are declared with #:
class DemoController
def index
#some_variable = "dlroW olleH"
#some_variable = backwards
end
private
def backwards
#some_variable.reverse
end
end
Rails automatically passes the controller's instance variables to the view context.
# /app/views/demos/index.html.haml
%h1= #some_variable
Guess what it outputs and I'll give you a cookie.
In your example #global_variable is nil since controller#sample_1 is not called - the request would go through controller#sample_2.
def sample_2
#global_variable = "Hello World"
end

Populate variable from partial template in Rails

I have this sort of function in a browser game i'm making :
def sendAllianceInvitationMessage(invited_user, alliance)
subject = 'Alliance Invitation'
body = 'You have received an invitation to join the alliance ' + alliance.name + '.'
body += ' Please visit the Alliance Menu in order to accept or reject alliance invitations.'
current_user.sendMessage(invited_user, subject, body, 'alliance invitation')
end
I'm really not comfortable with the idea of loading the body in this way. Is it possible to have a partial that receives parameters (like alliance.name in this code), produces the body content and pass es it to a string variable to be used in sendMessage?
You can render a partial and do a view to do that
body = render_to_string('send_alliance_invitation_message')
You just need pass your args like a view and you get the result in your body object

Rails: Prevent duplicate inserts due to pressing back button and save again

Think about a simple Rails scaffold application with a "new" action containing a form to add records to a database with a "save" button. After the "create" action the controller redirects to the "show" action, where the user can use the "edit" link to edit the just inserted record. So far, so simple.
But if the user instead uses the browser's back button after creating a record to get back to the "new" action, the browser shows the form with the values the user just has entered. Now he changes some values and presses "save" again. He thinks that this would change the record, but of course this creates a new record.
What is the preferred way to prevent such duplicate entries? I'm looking for a general solution, maybe based on cookies or JavaScript.
After some investigations I found a suitable solution based on cookies. Here it is:
In the controller's "new" action, a timestamp with the current time is generated and rendered in the form as hidden field. When the user submits the form, this timestamps gets back to the controller's "create" action. After creating the record, this timestamp is stored in the session cookie. If the user goes back to the "new" form via browser's back button, he gets a stale form, which means its timestamp is older than the one stored in the cookie. This is checked before creating the record and results in an error message.
Here is the controller code:
def new
#post = Post.new
#stale_form_check_timestamp = Time.now.to_i
end
def create
#post = Post.new(params[:post])
if session[:last_created_at].to_i > params[:timestamp].to_i
flash[:error] = 'This form is stale!'
render 'new'
else
#post.save!
#stale_form_check_timestamp = Time.now.to_i
session[:last_created_at] = #stale_form_check_timestamp
end
end
And here the form code:
- form_for #post do |f|
= tag :input, :type => 'hidden', :name => 'timestamp', :value => #stale_form_check_timestamp
= f.input :some_field
= .......
When I had that same problem I created this little gem that solves it. When the user hits back, he's redirected to the edit_path of the record, instead of going back to the new_path.
https://github.com/yossi-shasho/redirect_on_back
You can do something like:
def create
#user = User.new(params[:user])
if result = #user.save
redirect_on_back_to edit_user_path(#user) # If user hits 'back' he'll be redirected to edit_user_path
redirect_to #user
end
end
Your model validations will ensure things like email addresses are unique, but I think this is more about usability and experience than anything else.
Say you are talking about an account creation form. First of all, your form submit button should say something like "Create Account", instead of just "Submit". Then depending on whether it was successful or not, show a message like either "Account successfully created" or "There were errors creating your account". If the user sees this message, they will know what happened.
Sure you can't prevent someone from hitting the back button and hitting enter again, but you should design for the majority of use cases. If they happen to hit back, they will see the button that says "Create Account". You should probably have some other text on the page that says "Please sign up for a new account to get started".
Just my $0.02.
Session or cookie may result in sides effects.
I totally agree : if there is a way to validate with your model, it's the safest way to prevent duplicate records.
Still you can do 2 things. Prevent browser caching : fields will appear empty in the form when the user clicks on the back button. And disable the "Create" button when clicked.
= f.submit "Create", :disable_with => "Processing..."
When your user will press the back button the button will be disabled.
You can use validators to make sure that no duplicate values are inserted. In this case validates_uniqueness_of :field
If you for example want to prevent users from having the same email address you could put the following code in your user model.
validates_uniqueness_of :email
This checks the column for any previous entries that are the same as the one your trying to inert.
Good luck
base on #Georg Ledermann answer i make this little snip of code for redirect to edit path if the user hits back and then hits create.
#objects_controller.rb
def new
#object = Object.new
#stale_form_check = Time.now.to_i
end
def create
#object = Object.new(object_params)
#function defined in application_controller.rb
redirect_to_on_back_and_create(#object)
end
#application_controller.rb
private
def redirect_to_on_back_and_create(object)
if session[:last_stale].present? and session[:last_stale_id].present? and session[:last_stale].to_i == params[:stale_form_check].to_i
redirect_to edit_polymorphic_path(object.class.find(session[:last_stale_id].to_i)), alert: "Este #{object.model_name.human} ya ha sido creado, puedes editarlo a continuación"
else
if object.save
session[:last_stale] = params[:stale_form_check].to_i
session[:last_stale_id] = object.id
redirect_to object, notice: "#{object.model_name.human} Creado con éxito"
else
render :new
end
end
end
And finally add the #stale_form_check param to your form
<%= hidden_field_tag :stale_form_check, #stale_form_check %>
You could always abstracts this method where you need it, but in this way you could avoid lots of repetition in your project if you need this behavior in many parts
Hope it helps the next one, i used to use redirect_on_back gem, but it didn't work for me this time, the _usec param that this gem uses, was always been reset, so it can't compare in every time when it was need
Here's something that worked for me.
You will need to do 2 things: Create a method in your controller and add a conditional statement in that same controller under your 'create' method.
1) Your method should return the total count of that object from that user.
EX:
def user
current_user.object.count
end
2) Add conditional statement in your 'create' method.
EXAMPLE:
def create
#object = Object.create(object_params)
#object.save if user == 0
redirect_to x_path
end
I hope this helps!
Add html: { autocomplete: "off" } in your form_for like this:
<%= form_for #object, url: xxx_path, html: { autocomplete: "off" } do |f| %>

Easy breadcrumbs for RESTful rails application

Is there any helper method (Other than default rails breadcrumb) that generates bread crumb navigation dynamically for a particular page without having to pass trivial parameters in RESTful application? That is, something that figures out automatically where the user is based on the REST url she is visiting?
For above mentioned implementation, we need to pass parameters like
REST
<% add_crumb(‘Profile’, user_profile_path) %>
Current page
<% add_crumb(“My Incoming Messages”, request.path) %>
There must be a way to generalize the code so that no parameter passing is required and should work for all RESTful apps with minimal configuration.
Developed a simple hack. The method however assumes that there exists a method 'name' for every model object corresponding to each resource in the RESTful url. Whatever that the method 'name' returns is shown as breadcrumb name. If it is not found, it is shown as it is without making it link to anything. Separator used is '->' You may change it to suit your requirement.
def get_bread_crumb(url)
begin
breadcrumb = ''
sofar = '/'
elements = url.split('/')
for i in 1...elements.size
sofar += elements[i] + '/'
if i%2 == 0
begin
breadcrumb += "<a href='#{sofar}'>" + eval("#{elements[i - 1].singularize.camelize}.find(#{elements[i]}).name").to_s + '</a>'
rescue
breadcrumb += elements[i]
end
else
breadcrumb += "<a href='#{sofar}'>#{elements[i].pluralize}</a>"
end
breadcrumb += ' -> ' if i != elements.size - 1
end
breadcrumb
rescue
'Not available'
end
end
The method generally accepts request.url (Which given url of the current page) as the parameter. The method purposefully accepts the url for customization purposes. To generate the breadcrumb, simply add following code in your view -
<%= get_bread_crumb(request.url) %>
For the url /ideabox/2/idea/1, the bread crumb looks like
alt text http://www.imagechicken.com/uploads/1234855404069992300.png
Excuse me if code quality is not that great. I'm sure this code can be re-factored but I'm also sure you would be able to do that before using it.
Thanks.
The solution provided by chirantan is great. If you need breabcrumbs for namespaced controller and need to change the breadcrumbs depending on the namespace as well then try this. This is not perfect but refactor it as you need. It works for my project.
Define a new helper: navigation_helper.rb
module NavigationHelper
def navigation_add(title, url, namespace)
if defined? ##namespace and !##namespace.nil? and ##namespace == namespace
##navigation ||= []
else
##navigation = []
end
##navigation << {title: title, url: url} unless title == "Home"
new_nav = []
##navigation.each do |hash|
new_nav.push hash
if hash[:title].to_s == title.to_s
break
end
end
##navigation = new_nav
##navigation.uniq!
##namespace = namespace
end
def render_navigation
if (request.path_parameters[:controller].sub('/', '::_').camelize + 'Controller').classify.constantize.action_methods.to_a.include? 'index'
navigation_add controller_name.camelize.to_s, request.path_parameters.merge({action: 'index'}).except(:id), params[:controller].include?('/') ? params[:controller].split("/").first : nil
end
if defined? ##navigation
render partial: 'navigation/navigation', locals: { navs: ##navigation, namespace: ##namespace }
else
render text: ''
end
end
end
Then define a view for this helper _navigation.haml
- unless navs.blank?
%ol.breadcrumb
- navs.each_with_index do |nav, index|
- if index == 0
%li=link_to fa_icon('arrow-left', text: 'Go Back'), :back
- unless namespace.nil?
%li
%h4.inline= request.fullpath.split('/')[1].gsub('-', '_').camelize
= fa_icon('angle-double-right')
%li= link_to_unless (nav[:title] == controller_name.camelize and action_name == 'index'), fa_icon(nav[:title].downcase.singularize, text: nav[:title]), nav[:url]

Resources