How do you do automated testing with a webforms app that uses Froms Authentication? - forms-authentication

I have an webforms application that I would like to create some automated tests for. This application currently implements Forms Authentication.
What is the best way to accomplish this?

You can use an automated tool such as Selenium or Watin to help drive the test through Internet Explorer or Firefox. At my company, we automate all front end tests using C#, Watin, and Gallio (mbUnit).
You will need to use a tool such as Developer Tools on IE to discover the names/ids of web controls such as textboxes and buttons. Once you have them, you can create Watin objects to represent them. Watin provides basic classes such as Button and TextField.
public class SignInPage
{
public Button SignInButton { get { return Document.Button(Find.ByName(new Regex("login"))); } }
public TextField UserNameEmailTextField { get { return Document.TextField(Find.ByName(new Regex("userNameEmail"))); } }
public TextField PasswordTextField { get { return Document.TextField(Find.ById(new Regex("password"))); } }
............
}
Then you will drive the test through the SignInPage object.
Browser.Page<SignInPage>().UserNameEmailTextField.Value = userName;
Browser.Page<SignInPage>().PasswordTextField.Value = password;
Browser.Page<SignInPage>().SignInButton.Click();
This same procedure is also easily accomplished with Selenium.

Related

JavaFX not available, what now?

I have a JavaFX application, but when people try to run it nothing happens because they got no JavaFX on their system, because they are using OpenJDK for example.
What can I do to inform people about the problem?
Best way would be to have an Alert informing the user about that, is there a way to do this with basic Java functionality?
You can use a Swing App to start and check if Java FX is avalaible like this:
private static boolean isJavaFxAvalaible() {
try {
ClassLoader.getSystemClassLoader().loadClass("javafx.application.Application");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
If this is true, just load your Main JavaFX, here's an example:
Launch JavaFX application from another class
hope this can help you.

Preparing for Internationalization of Asp.net MVC website

I'm going to start a website which I know is going to be presented in multiple languages. However, for the first version we're only going to need the English version. Once the features are all working, we'll add the other languages.
Unfortunately since there are not enough enough features baked into Asp.Net Core, we have to use the Asp.Net MVC 5 for the website. My question has 2 parts:
Right now, which practice is considered the best approach for this? Using resource files and loading them in razor pages? Using a framework? Can we use the new localization and globalization features of Asp.Net MVC 6 somehow? Or is there a better alternative? I personally hate using the resource files. It adds too much clutter to the code.
Would you suggest just using plane text for now and then adding the Internationalization features to the website or start now and only add the translations?
I would use resource files, seems to be the easiest solution. You can also use a Database resource provider, so you have less clutter.
If you start with plain text, it will get more complicated and cumbersome to add the translations later. So I would not do that.
We use Smart internationalization for ASP.NET.
Features
Localize everything: HTML, Razor, C#, VB, JavaScript, .NET attributes
and data annotations, ...;
SEO-friendly: language selection varies the URL, and Content-Language is set appropriately;
Automatic: no URL/routing changes required in the app;
High performance, minimal overhead and minimal heap allocations; Unit testing support;
Smart: knows when to hold them, fold them, walk away, or run, based on i18n best practices.
How I use i18n in the project step by step:
Add the I18N nuget package to your MVC project.
in Web.config:
Add a folder named "locale" to the root of your site. Create a subfolder for each culture you wish to support. For example, /locale/fr/.
copy i18n.PostBuild.exe into locale folder
Right click on tne project name --> Properties --> Build Events:
in Post-build event command line:
"$(TargetDir)i18n.PostBuild.exe" "$(ProjectDir)\web.config"
In views use [[[some text]]] to translate it later
Build the project
Refresh Solution Explorer and push Show All Files
Include all files in "locale" folder into the project
Provide translation of the words in locale\fr\messages.po
In Global.aspx add :
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//other app start code
UrlLocalizer.UrlLocalizationScheme = UrlLocalizationScheme.Void;
}
}
Create DefaultController :
public class DefaultController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (Session["currentLanguage"] == null)
{
Session["currentLanguage"] = "en";
}
}
}
In HomeController add inheritance of DefaultController and SwitchLanguage(string lang):
public class HomeController : DefaultController
{
public HomeController() : base()
{
[AllowAnonymous]
public async Task<ActionResult> SwitchLanguage(string lang)
{
LocalizedApplication.Current.DefaultLanguage = lang;
Session["currentLanguage"] = lang;
return Redirect(Request.UrlReferrer.PathAndQuery);
}
}
}
In navigation bar View (_LoginPartial.cshtml in my case) add links to switch between languages:
#if (Session["currentLanguage"].ToString() == "fr")
{
<li class="navItem">#Html.ActionLink("EN", "SwitchLanguage", "Home", new { lang = "en", area = "" }, null)</li>
}
else
{
<li class="navItem">#Html.ActionLink("FR", "SwitchLanguage", "Home", new { lang = "fr", area = "" }, null)</li>
}
Build project, Start in Browser and enjoy!!!
see some help in:
https://www.codeday.top/2017/09/19/42409.html

Display Content based on situation (Xamarin.Forms)

I am creating an app using Xamarin Forms. I have a MainTab page that displays all the 4 tabs. There is one specific tab call Me tab.
As of now the Me Tab displays the user's profile. However, when the user is not logged in, it my UserLogin page should be displayed instead. How do I do that in Xamarin forms?
You can achieve this in various ways. If you're using a MVVM approach the most straight forward solution would be to set a binding in your viewmodel indicating user logging. Based on that you can set your
tabbedPage.CurrentPage = TheTabPageYouWant.
If you're using codebehind, just use in your ;
public bool UserLogged
{
get { return _userLogged; }
set
{
_userLogged = value;
if (_userLogged)
{
tabbedPage.CurrentPage = UserProfilePage.
return;
}
tabbedPage.CurrentPage = LogInPage.
}
I strongly recommend any Xamarin.Forms book and MVVM techniques for you.
Don't hesitate to ask any further questions.

Handling complex navigation in Flex

I am building a complex Flex app, and now I am at the point where navigation becomes a problem. I make use of Viewstacks with a Menu Bar, but I am not sure how to clearly structure this.
Depending on the logged in User and chosen Company by the user, he can see different pages. For now I restricted this hiding the appropriate buttons in the Menu Bar. However, not just the menu bar, but also buttons/links from within the app should be able to navigate to each existing page.
When I am loading up an existing page, it needs some initialization (depending on the context it is loaded from). In addition, when a company is chosen, I need to load the status from the backend, and depending on this status a specific page might be visible.
Are there any guidelines how to tackle more complex navigation/site hierarchies in Flex?
Now I am having all my views in a viewstack in the Application, and refer to it with Application.application.appViews.selectedChild -> but that's obviously not best practice, since it violates encapsulation.
Was thinking of implementing some sort of State Machine, which takes care of all this, but not quite sure it this would make sense, or if there is any better way.
Thanks guys,
Martin
If it's really complex, you might want to consider breaking your application up into modules.
Also, Mate is a great Flex framework for handling complex communication and navigation. Mate's EventMaps help you centralize the communication and logic between components, modules, etc. And, it keeps you away from the dreaded Application.application references.
Even if you don't use a framework like Mate, you can avoid the Application.application references by having components dispatch custom events that bubble up to the top-level of your application. The top level of the application can listen and catch these events and act on them. I've found this to be a much more flexible approach. I avoid Application.application as much as possible!
If you have a complex menu bar that needs to enable / disable a lot of buttons or options based on many different logic conditions, the State pattern is a decent way to handle it. I built an enterprise-level app that had a "Word-like" button bar at the top...and there were so many different conditions that affected the states of the buttons that I had to centralize the logic in one place. At first I didn't use the State pattern and maintaining the code was a difficult chore. One day, I bit the bullet and re-factored all the conditional logic into a StateManager class. It definitely made life easier from there on out.
Again, you might want to consider using Custom Events to broadcast important events to your application. You can make these events bubble up to the Application level. Then, by adding event listeners at the Application level, you can capture and respond to these events and target components or modules from the Application level. This gives you a central location for handling events and "directing traffic". It also prevents the tight-coupling of the Application.application approach. (Which quickly becomes a nightmare as your application grows and scales!)
For example, your StateManager can contain the case statements for deciding which state your application needs to be in. Once the decision about the current state is determined, you would dispatch a custom StateEvent. (Which might have properties like StateEvent.STATE_CHANGED and StateEvent.CURRRENT_STATE) This event can bubble up to the Application level and be caught by a listener. The listener then calls a method to load / change the state.
Does that clarify it for you? If not, perhaps I can spend an hour or two putting together a little sample.
Let me know,
=Bryan=
I can give you the approach I used for some of your sub-questions, the problem of initializing a page at runtime and how to encapsulate navigation.
For page initialization, the issue I came across is that it's not always known once you navigate to a page whether certain elements should be shown, since it not-only depends on overall user permissions, but also permissions against the currently-selected data. And if the information needed to determine this must be loaded from the server, you cannot show the page as-is while loading the information. So we created a control called LoadingPanel, which is a container that can cover content with a loading indicator until additional information has been received. Here's a shortened version of the ActionScript:
[DefaultProperty("children")]
public class LoadingPanel extends ViewStack
{
public function LoadingPanel()
{
this.resizeToContent = false;
super();
}
public function get children():Array { return _children }
public function set children(value:Array):void { _children = value; }
public function get loadingImageStyle():String {
return _loadingImgStyle; }
public function set loadingImageStyle(value:String):void {
_loadingImgStyle = value;
if (_loadingIndic)
_loadingIndic.loadingImageStyle = value;
}
public function showLoadingIndicator():void
{
if (_loadingIndic)
{
super.selectedChild = _loadingIndic;
}
else
{
_pendingLoadingIndic = true;
var me:LoadingPanel = this;
var listener:Function = function(event:Event):void
{
if (me._pendingLoadingIndic)
me.showLoadingIndicator();
}
addEventListener(FlexEvent.CREATION_COMPLETE, listener);
}
}
public function hideLoadingIndicator():void
{
_pendingLoadingIndic = false;
if (_content)
{
super.selectedChild = _content;
}
else
{
var me:LoadingPanel = this;
var listener:Function = function(event:Event):void
{
me.hideLoadingIndicator();
}
addEventListener(FlexEvent.CREATION_COMPLETE, listener);
}
}
public function waitForEvent(target:EventDispatcher, event:String):void
{
_eventCount++;
showLoadingIndicator();
var me:LoadingPanel = this;
target.addEventListener(
event,
function(evt:Event):void
{
me._eventCount--;
if (!me._eventCount)
{
me.hideLoadingIndicator();
}
}
);
}
override public function addChild(child:DisplayObject):DisplayObject
{
var result:DisplayObject = child;
if (_content)
{
result = _content.addChild(child);
invalidateDisplayList();
}
else
{
if (!_children)
{
_children = [];
}
_children.push(child);
}
return result;
}
override protected function createChildren():void
{
super.createChildren();
if (!_content)
{
_content = new Box();
_content.percentWidth = 1.0;
_content.percentHeight = 1.0;
super.addChild(_content);
}
if (!_loadingIndic)
{
_loadingIndic = new LoadingIndicator();
_loadingIndic.percentWidth = 1.0;
_loadingIndic.percentHeight = 1.0;
_loadingIndic.loadingImageStyle = _loadingImgStyle;
super.addChild(_loadingIndic);
}
if (_children)
{
for each (var child:DisplayObject in _children)
{
_content.addChild(child);
}
}
}
private var _loadingImgStyle:String = "loadingIndicatorDark";
private var _loadingIndic:LoadingIndicator = null;
private var _content:Box = null;
private var _children:Array = null;
private var _pendingLoadingIndic:Boolean = false;
private var _eventCount:int = 0;
}
We typically used these by wrapping a LoadingPanel around content then calling the panel's waitForEvent method. Typically, the event we'd wait for is for a web service response to come in. The class also lets you wait on multiple events before it will show its children.
Another recommendation I would make for your project is that you look into deep linking in Flex. Our users appreciated being able to bookmark a resource/location in our complex Flex application as well as being able to hit refresh in their browser and return to the same "page" they were on. But implementing deep linking also helped me out for one of the problems you mentioned; how do you send the UI to a specific page in an encapsulated manner? The way we did it is by raising a bubbling navigation event containing a destination "URL." A top-level navigation "manager" then handled interpreting the URL and "sending" the user to the appropriate area.
Hopefully this will give you some ideas for some of the challenges you face.

Can you do ajax without using ASP.net ajax toolkit?

Can you do ajax on ASP.net webform without using ajax toolkit? (Please post a example link)
yes... see my example in this post
AJAX - How to Pass value back to server
This can perform much better than ASP.NET ajax, but does take longer to code.
Sure. People have been doing ajax for years before the term ajax was even coined. Jquery is a popular library that you can use to make calls back to the server without a page refresh.
Certainly you can! What I did in .NET 1.1 (before ASP.Net Ajax was released) was to define an HttpHandler to listen on calls to ajax.aspx, run the appropriate methods, and spit back out the result. I used the Prototype library to make the Ajax call, though you could use any other, or do it by hand.
I'm going by memory, but here's the code I used (for .NET 2.0, but you get the idea):
// client-side js:
var foo = new Ajax.Request('ajax.aspx',
{
method:'get',
parameters: { method: 'GetFive' },
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
// web.config:
<httpHandlers>
<!-- pre existing handlers go here -->
<add verb="GET" path="ajax.aspx" type="Fully.Qualified.Name.AjaxHandler, AssemblyName" validate="false" />
</httpHandlers>
// AjaxHandler.cs
public class AjaxHandler : IHttpHandler {
internal delegate object AjaxFunction();
private Dictionary<string, AjaxFunction> functions;
public bool IsReusable {
get { return true; }
}
public void ProcessRequest(HttpContext context) {
this.functions = new Dicionary<string, AjaxFunction>();
this.functions.Add("GetFive", delegate() {
return 5;
});
string functionName = context.Request["method"];
AjaxFunction func = this.functions[functionName];
if (func != null) {
object val = func();
context.Response.Write(val);
}
}
}
[Big note: the above is untested and not really designed well, and may not even compile, but it should give you the right idea.]
Here's a popular tool: AjaxPro.
As others have noted, you can code the entire thing yourself using XmlHttpRequest objects and javascript. But if your app will be using very sophisticated techniques, writing the code yourself becomes quite tedious. The tools have become much more powerful and easy to use.
Parenthetically, there are two elements to ASP.Net Ajax. One is the Ajax Extensions that are included in Visual Studio 2008 and can be added to Visual Studio 2005. This can be used for much more functionality than the "toolkit". Things like partial page refreshing and retrieving data without performing a full postback. The other is the Ajax Control Toolkit, which is a separate download. The "toolkit" primarily includes fancy controls, especially ones with DHTML effects (show, hide, mimic animation).
Oh absolutely.
There are libraries such as jQuery that you can use in your ASP.NET forms instead of UpdatePanel and all the paraphernalia that surrounds it.
Where I used to work we were doing AJAX long before there was a word for it. This was in the days when our stuff only used to work in IE :-)
One thing you need to do in ASP.NET forms where you're using ASP.NET server controls is use the correct client ID that the server generates for your controls when referencing them from javascript. So if you have a label with an ID of say 'telephoneNumber', you need to reference it as <%=telephone.ClientID %>. e.g.
$("#<%=telephoneNumber.ClientID %>").attr("disabled", "disabled");
With libraries such as jQuery you can still call your ASP.NET webservices but you're probably better of investigating WCF and JSON serialisation.
You don't have to throw away everything in the ASP.NET ajax bits, I still make calls to web services using script services. It's a half way house until I can replace with JSON:
http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
Ajax just means while user is looking at your web page, with javascript, go back to the server and fetch something else. Then update the page with what you fetched, using javascript, the DOM.
The XMLHttpRequest object is nice, but even before it, you could do the same thing using a hidden IFRAME....
Here is all the javascript code you need to get started:
function GetXmlHttpObject()
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
// do something with xmlHttp.responseText
}
}
function SendAsyncHttpRequest()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
return
}
var url = "http://YOUR_URL"
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
YES!
There are a "gazillion" alternatives to ASP.NET AJAX out there. Most of them are better in fact too. You might want to check out my project; Ra-Ajax for your needs :)

Resources