Using own classes inside razor code - c#

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.

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

"The name does not exist in the current context"

I get the following error;
The name 'Request' does not exist in the current context
using System;
using System.Web;
using System.Web.UI;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Microsoft.Exchange.WebServices.Data;
namespace Exchange101
{
// This sample is for demonstration purposes only. Before you run this sample, make sure that the code meets the coding requirements of your organization.
class Ex15_CreateMeetingOnBehalfOfPrinciple_CS
{
static ExchangeService service = Service.ConnectToService(UserDataFromConsole.GetUserData(), new TraceListener());
protected void Page_Load(object sender, EventArgs e)
{
var request = HttpContext.Current.Request.QueryString["source"];
HttpRequest q = Request;
NameValueCollection n = q.QueryString;
if (n.HasKeys())
{
string k = n.GetKey(0);
if (k == "one")
{
string v = n.Get(0);
}
if (k == "two")
{
string v = n.Get(0);
}
}
}
I'm an absolute newbie and have researched the error but am confused as to which assembly I might be missing as a reference.
issue may be here
var request = HttpContext.Current.Request.QueryString["source"];
HttpRequest q = Request;
your variable name is request bt you are using Request
change this as
var request = HttpContext.Current.Request.QueryString["source"];
HttpRequest q = request;
this wil solve your issue
Change this line:
class Ex15_CreateMeetingOnBehalfOfPrinciple_CS
to this:
class Ex15_CreateMeetingOnBehalfOfPrinciple_CS : System.Web.UI.Page
It looks like the problems you're getting are from properties you should be inheriting from that class.
If you are meaning HttpWebRequest, you should include the namespace
using System.Net;

unhandled exception c# dll

I tring to test a new dll that I've build for c#
private void button1_Click(object sender, EventArgs e)
{
String [] first = UserQuery.Get_All_Users();
//MessageBox.Show(first);
}
but I get the following error at String [] first = UserQuery.Get_All_Users();
An unhandled exception of type 'System.NullReferenceException' occurred in User_Query.dll
Additional information: Object reference not set to an instance of an object.
I been tring to figure this one out for hours but can't find any null varibles
I post my dll in case the dll is wrong
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace User_Query
{
public class UserQuery
{
public static string[] Get_All_Users()
{
string[] names = new string[10];
var path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
byte i = 0;
foreach (var name in userNames)
{
Console.WriteLine(name);
names[i] = name;
i++;
}
return names;
}
}
}
}
There is a problem with your. path variable... since there should be \\ instead of //
The problem here turned out not to be the code but be VS2010 not loading the dll. This happen because I decided to change the program from using the dll from the debug to the release version but I did not clean the project after doing it and therefore the program was not correctly loading the dll. All that need to be done was clean the project

Razor Syntax / WebMatrix - C# Question

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

Getting DLLs in WinForms application

I have to create a class that will load all the dll's from repository and check whether
they are inheriting from IMFServicePlugin interface and returns the
valid dlls.
that I have done using this...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms.ComponentModel;
using MFDBAnalyser;
namespace MFDBAnalyserAssemblyValidator
{
public class MFDBAnalyserAssemblyValidator
{
static void Main(string[] args)
{
List<string> assemblyNames = new List<string>();
Assembly[] oAssemblies = new Assembly[args.Length];
for (int assemblyCount = 0; assemblyCount < args.Length; assemblyCount++)
{
oAssemblies[assemblyCount] = Assembly.LoadFile(args[assemblyCount]);
try
{
foreach (Type oType in oAssemblies[assemblyCount].GetTypes())
{
// Check whether class is inheriting from IMFServicePlugin.
if (oType.GetInterface("IMFDBAnalyserPlugin") == typeof(IMFDBAnalyserPlugin))
{
assemblyNames.Add(args[assemblyCount].Substring(args[assemblyCount].LastIndexOf("\\") + 1));
}
}
}
catch (Exception ex)
{
lblError.Text = "ERROR";
}
}
// Passing data one application domain to another.
AppDomain.CurrentDomain.SetData("AssemblyNames", assemblyNames.ToArray());
}
}
}
but this was for loading the dll from the repository but I also want to store these dll in another ORM class.
Can anybody help me out...
If possible plz provide some links so that I can get a sufficient idea of how dll works for an windows/desktop application.
At a first tip you should use Assembly.ReflectionOnlyLoad(). Cause if you load the assembly by using Assembly.LoadFile() the assembly will automatically be put into your local AppDomain!

Categories

Resources