Razor Syntax / WebMatrix - C# Question - c#

In Windows Forms I can create a class file called 'Authentication.cs' with the following code:
public class Authentication
{
public string Name;
internal bool Authenticate()
{
bool i = false;
if (Name == "Jason")
{
i = true;
}
return i;
}
}
In WebMatrix, I can insert a new Class file, called 'Authentication.cs', and insert the above code.
And in my default.cshtml file, I do this:
<body>
#{
Authentication auth = new Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp");</p>
}
}
</body>
But it won't work! It works for the WinForms desktop app, but not in WebMatrix. I don't know why it's not working. The error message is:
"The namespace Authenticate does not
exist. Are you sure you have
referenced assemblies etc?"
So, then at the top of my default.cshtml file I tried this:
#using Authentication.cs;
Which led to the exact same error!
There's no documentation that I can find anywhere that tells you how to "include" a class file into your WebMatrix pages.
Any help is appreciated,
Thank you!

You import a namespace, not a file. So; what namespace is Authentication in? For example:
#using My.Utils.Authentication.cs;
Also - you want to drop the ; in the razor call:
<p>#auth.Authenticated("jasonp")</p>
You can also provide the fully qualified name in the code:
#{
var auth = new My.Utils.Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp")</p>
}
}
(aside: are you intentionally calling the same method twice with the same values?)

Just drop the cs file in you App_Code directory
then do something like this
#{
Authentication auth = new Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp");</p>
}
}
No need to add a using.
Additionally if you wanted to use a .dll then you would need the using
#using NameSpace.Authenication
#{
Authenticated auth = new Authenicated();
}
#if(#auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp")</p>
}

Create a file named linkRef.cs
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class linkRef
{
public linkRef() {
//
// TODO: Add constructor logic here
//
}
}
Put it in a folder App_code then by dot net 2012 publish to bin then upload bin folder

Related

How to fix The controller for path '/' was not found or does not implement IController

I just deployed a new controller to my production environment. For some reason, the controller does not get called. All other controllers on the site work fine. This is the only one that is failing. What I keep getting is the error:
Error rendering controller BlogListing.GetIndex: Could not create
controller: 'BlogListing'. The controller for path '/' was not found
or does not implement IController
I've spent about 3 hours trying to troubleshoot this. I have:
Added debug code into the controller to see if it is in fact being called. My debug statements does not get hit.
Verified the name of the controller is correct
I am using the default MVC routing.
Thinking that it might be a missing dependent dll, I copied all of the dlls from my production environment (where it is not working) to my local environment and it came right up
Checked file system permissions thinking that somehow it couldn't be read.
I did look at other posts regarding similar issues but none of those solutions worked or were not applicable
namespace Portal.Features.Blog.Controllers
{
using Glass.Mapper.Sc;
using Glass.Mapper.Sc.Web.Mvc;
using Sitecore.Data.Items;
using System;
using System.Linq;
using System.Web.Mvc;
using Portal.Foundation.Blog;
using portal.ct.gov.Models;
using Portal.Features.Blog.Models;
using portal.ct.gov.Business;
public class BlogListingController : GlassController
{
public ActionResult GetIndex(string keyword = "", string page = "", string author = "")
{
Sitecore.Diagnostics.Log.Info("Blog Controller found", "portal.ct.gov");
try
{
SitecoreContext scContext = new SitecoreContext();
Item contextItem = scContext.GetCurrentItem<Item>();
Item blogHome = null;
//Get Blog Root
if (contextItem != null)
{
blogHome = contextItem.Axes.SelectSingleItem("ancestor-or-self::*[##templatename = 'Blog Section']");
}
var sKeyword = !string.IsNullOrEmpty(HttpContext.Request.QueryString[Constants.QueryStrings.SearchKeyword]) ? HttpContext.Request.QueryString[Constants.QueryStrings.SearchKeyword] : string.Empty;
var blogAuthor = !string.IsNullOrEmpty(HttpContext.Request.QueryString["author"]) ? HttpContext.Request.QueryString["author"] : string.Empty;
var blogCategory = !string.IsNullOrEmpty(HttpContext.Request.QueryString["category"]) ? HttpContext.Request.QueryString["category"] : string.Empty;
var blogPage = !string.IsNullOrEmpty(HttpContext.Request.QueryString["page"]) ? HttpContext.Request.QueryString["page"] : "1";
var model = GetBlogListing(blogHome, sKeyword, blogCategory, blogAuthor, Convert.ToInt32(blogPage));
return View("/views/blog/BlogResultsMain.cshtml", model);
}
catch(Exception ex)
{
Sitecore.Diagnostics.Log.Error("Error processing bloglisting-->getINdex " + ex.Message, ex, "portal.ct.gov");
return View("/views/blog/BlogResultsMain.cshtml");
}
}
}
Any help is appreciated. Please note that I am using Sitecore CMS.
It is worth checking the cached MVC-ControllerTypeCache.xml file in folder c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\NAMEOFYOURAPP\xxxxx\xxxxxxxx\UserCache\.
If you can't find your controller there, remove the cached xml file and restart your website. More details you can find here

How to load a local html file in a xamarin forms webview

I am trying to load a html file that is in the same path as class i'm working with Via a web view in xamarin forms when I run the app I get a white screen and nothing loads here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App.Plan
{
public partial class Tornado : ContentPage
{
public Tornado()
{
InitializeComponent();
var browser = new WebView
{
Source = "local.html"
};
}
}
}
I realize this is old, but the documentation is maybe not entirely clear when it comes to local files so I thought I'd share my thoughts. Hopefully it's helpful to anyone who stumbles here.
The documentation states:
To display local content using a WebView, you'll need to open the HTML file like any other, then load the contents as a string into the Html property of an HtmlWebViewSource.
The key thing to note is that the WebView's Source property is ONLY for external URLs or HtmlWebViewSource. You cannot put a local URL in the Source property. The phrasing "you'll need to open the HTML file like any other" means (as it states shortly after) that you need to load the contents of the file from disk into a variable using a full file path, not URL.
The question then becomes "What about links to other local files?" That's where the BaseUrl property of HtmlWebViewSource comes into play. The documentation addresses this by stating the following:
Although the first page has been loaded, the WebView has no knowledge of where the HTML came from. That is a problem when dealing with pages that reference local resources. Examples of when that might happen include when local pages link to each other, a page makes use of a separate JavaScript file, or a page links to a CSS stylesheet.
In other words, any links to local resources in your HTML will be prepended with the BaseUrl by the Webview automatically.
To sum things up
Create the IBaseUrl Interface in your shared project
public interface IBaseUrl {
string Get();
}
Create the platform-specific implementations of IBaseUrl in each platform project
iOS:
[assembly: Dependency (typeof (BaseUrl_iOS))]
namespace WorkingWithWebview.iOS
{
public class BaseUrl_iOS : IBaseUrl
{
public string Get()
{
return NSBundle.MainBundle.BundlePath;
}
}
}
Android
[assembly: Dependency (typeof(BaseUrl_Android))]
namespace WorkingWithWebview.Android
{
public class BaseUrl_Android : IBaseUrl
{
public string Get()
{
return "file:///android_asset/";
}
}
}
UWP
[assembly: Dependency(typeof(BaseUrl))]
namespace WorkingWithWebview.UWP
{
public class BaseUrl : IBaseUrl
{
public string Get()
{
return "ms-appx-web:///";
}
}
}
Make sure your HTML files are in the appropriate folders and have the proper Build Action
iOS: Resources, build action: "BundleResource"
Android: Assets, build action: "AndroidAsset"
UWP: project root, build action: "content"
Make sure the WebView has a height and width request or it may not render:
It may be necessary to set the WidthRequest and HeightRequest properties of the WebView to see the HTML content, depending upon the layout the WebView is a child of. For example, this is required in a StackLayout.
Once that setup is done, you can put it into action in your shared project. Here's a simplified example:
// Use DI function to get the BaseUrl for the platform
var baseUrl = DependencyService.Get<IBaseUrl>().Get();
// You could append subfolders here if you don't
// want all the HTML files mixed with other resources:
// var baseUrl = System.IO.Path.Combine(DependencyService.Get<IBaseUrl>().Get(), "subfolder");
// Define the location of your initial HTML page using the base url
var initialHtmlPath = System.IO.Path.Combine(baseUrl, "index.html");
// Create the viewsource, loading the first HTML file as a string
var localHtmlViewSource = new HtmlWebViewSource();
localHtmlViewSource.BaseUrl = baseUrl;
localHtmlViewSource.Html = System.IO.File.ReadAllText(initialHtmlPath);
// Set the webview to use the local source
HelpWebView.Source = localHtmlViewSource;
Xamarin has docs in relation to this:
https://developer.xamarin.com/guides/xamarin-forms/user-interface/webview/
var browser = new WebView();
var htmlSource = new HtmlWebViewSource();
htmlSource.Html = #"<html><body>
<h1>Xamarin.Forms</h1>
<p>Welcome to WebView.</p>
</body></html>";
browser.Source = htmlSource;
Here is official sample in github
WorkingWithWebview
tabs.Children.Add (new LocalHtml {Title = "Local" });
tabs.Children.Add (new LocalHtmlBaseUrl {Title = "BaseUrl" });
tabs.Children.Add (new WebPage { Title = "Web Page"});
tabs.Children.Add (new WebAppPage {Title ="External"});
Second tab may help.

Copy Content from one Word Document to another in C# (MVC)

I am new here in the forum and I just start to work in a new web application on Visual studio 2013. I need to create an application that copy all the content from one Word Document to another. I had found this plugin that should make the job but I dont know how to put it in my code and make it work. I need to do it in a MVC application, so maybe I am not putting the code in the right place (now it is in the Model). Someone can help me telling me how to make it work? Please see the code that I have:
using Spire.Doc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DocumentApplication.Models
{
public class HomeModel
{
public string Message { get; set; }
}
public class CopyDocument
{
Document sourceDoc = new Document("source.docx");
Document destinationDoc = new Document("target.docx");
foreach (Section sec in sourceDoc.Sections)
{
foreach (DocumentObject obj in sec.Body.ChildObjects)
{
destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());
}
}
destinationDoc.SaveToFile("target.docx");
System.Diagnostics.Process.Start("target.docx");
}
public class OpenDocument
{
Document document = new Document(#"C:\Users\daniel\Documents\ElAl-DRP.doc");
}
}
I cannot compile this because I have an error on the "foreach" line that says: "Invalid token 'foreach' in class' struct' or interface member declaration".
Please help me.
Thanks in advance
Okay this is pretty rough but it at least works.
I could not make the example from the Spire work, I had to make some changes.
This example will take an uploaded file, save it in to the "AppData/uploads" folder then it will create a copy of that saved file in the "AppData/copies" folder.
My Changes
the way we create the destination Doc in memory then save later.
Create a new section in the "foreach" loop
Add the cloned sections to the new section
List item
Document Format on the SaveDocument Method (This is a huge
assumption)
Controller
using System.IO;
using System.Web;
using System.Web.Mvc;
using Spire.Doc;
using Spire.Doc.Collections;
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
var outputPath = Path.Combine(Server.MapPath("~/App_Data/copies"), fileName);
var sourceDoc = new Document(path);
var destinationDoc = new Document();
foreach (Section sec in sourceDoc.Sections)
{
var newSection = destinationDoc.AddSection();
foreach (DocumentObject obj in sec.Body.ChildObjects)
{
newSection.Body.ChildObjects.Add(obj.Clone());
}
}
destinationDoc.SaveToFile(outputPath, FileFormat.Docx);
}
return View();
}
}
View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file"/>
<button type="submit">Save</button>
}

Using own classes inside razor code

I have in my funcs.cs file:
using System;
using System.Collections.Generic;
using System.Web;
public static class AuthData
{
public const string USERNAME = "zheref";
public const string PASSWORD = "Altairis";
}
And I'm trying to access the USERNAME and PASSWORD constants in my AuthData class from my Razor Code (auth.cshtml file):
#{
if(IsPost)
{
var u = Request.Form["username"];
var c = Request.Form["password"];
if(u == AuthData.USERNAME && c == AuthData.PASSWORD)
{
Response.Redirect("~/default");
}
else
{
Response.Redirect("~/logon");
}
}
}
This is generating a Compilation Error:
"An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately."
If that's not the way I'm not sure how to do that. Thanks.
You need to put your funcs.cs file in your App_Code folder, if it doesn't exist create it. This assumes that all namespaces are resolvable and you don't need any using statements in your razor file.

How to access database in lightswitch in other class?

I just don't know how to explain this clearly. So I create a simple image pattern of what I did.
My question is, how would I be able to access my database in other class in LS?
I've been searching on net, but I didn't found any solution. I hope I'll find it here.
Thanks!.
Any suggestion is already appreciated.
Thanks for the answer Bryan, but I found the answer on my problem here Richard Waddell
Here is what I did to achieve my goal.
Switch your LS project to file view
Go to "Common" project, under "UserCode" folder, create a class (e.g. Authenticate.cs) and put this codes.
The code follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
namespace LightSwitchApplication
{
public class Authenticate
{
public static adminuser GetCurrentUser()
{
adminuser userFound = (from useritem in
Application.Current.CreateDataWorkspace().basecampcoreData.adminusers
where useritem.LoginID == Application.Current.User.Name
select useritem).SingleOrDefault();
if (userFound != null)
return userFound;
else
return null;
}
}
}
Then you can now call the Authenticate.GetCurrentUser() anywhere in the project.
Thanks!
The main difference is the first set of code that works is running inside a screen. For your Authenticate class, you need to do the following steps to access the Database.
Note: I'm assuming that your datasource has the default name of ApplicationData since you hid the name, if not, make the corresponding changes. If it's a completely different datasource, change "_IntrinsicData" in the steps below)
These steps are taken from the Lightswitch Help Website
Navigate to ..ServerGenerated\GeneratedArtifacts (in the LightSwitch project) and click on ApplicationData.cs and Add As Link.
Add the following code below, this code dynamically creates a connection to the database. LightSwitch uses “_IntrinsicData” as it’s connection string.
private ApplicationDataObjectContext m_context;
public ApplicationDataObjectContext Context
{
get
{
if (this.m_context == null)
{
string connString =
System.Web.Configuration.WebConfigurationManager
.ConnectionStrings["_IntrinsicData"].ConnectionString;
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata =
"res://*/ApplicationData.csdl|res://*/ApplicationData.ssdl|res://*/ApplicationData.msl";
builder.Provider =
"System.Data.SqlClient";
builder.ProviderConnectionString = connString;
this.m_context = new ApplicationDataObjectContext(builder.ConnectionString);
}
return this.m_context;
}
}
You should be able to access it through Context.adminusers

Categories

Resources