MVC 5 - controller can't see a namespace I need - c#

I am remaking an app in MVC and have created a folder called App_Code. Inside the folder is a file called SessionManager.cs. I want to reference it in my controller but it can't see the namespace and I am baffled.
My controller
using System;
using System.Web.Mvc;
using AMT2012.AmtService;
using AMT2014_Prototype.App_Code;
namespace AMT2014_Prototype.Controllers
{
public class EnquiryController : Controller
{
[HttpGet]
public ActionResult _EnquiryBreadCrumb()
{
var finishedStepNumber = 1;
if (SessionManager.GetSession(SessionManager.FinishedStepNumber) != null)
{
// trackbarEnquirySteps.Position = (int)SessionManager.GetSession(SessionManager.FinishedStepNumber);
// trackbarEnquirySteps.ClientSideEvents.PositionChanging =
//"function(s,e){ if (e.currentPosition < e.newPosition) { if (e.newPosition <= " + trackbarEnquirySteps.Position + ") { e.cancel = false; } else { e.cancel = true; } } else { e.cancel = false; } }";
finishedStepNumber = Convert.ToInt32(SessionManager.GetSession(SessionManager.FinishedStepNumber)) + 1;
}
switch (finishedStepNumber)
{
case 1:
imgStepStatus.ImageUrl = "~/AMTImages/Step1.png";
break;
case 2:
imgStepStatus.ImageUrl = "~/AMTImages/Step2.png";
break;
case 3:
imgStepStatus.ImageUrl = "~/AMTImages/Step3.png";
break;
}
if (SessionManager.GetSession(SessionManager.NewEnquiryType) != null)
{
var enqType =
(EnquiryTypeDto.EnumEnquiryTypeDto)(SessionManager.GetSession(SessionManager.NewEnquiryType));
switch (enqType)
{
case EnquiryTypeDto.EnumEnquiryTypeDto.EMail:
imgEnqTypeHeader.ImageUrl = "~/AMTImages/Icons/email_add.png";
imgEnqTypeHeader.ToolTip = "New Email Enquiry";
lblEnquiryTypeHeader.Text = "New Email Enquiry";
break;
case EnquiryTypeDto.EnumEnquiryTypeDto.Letter:
imgEnqTypeHeader.ImageUrl = "~/AMTImages/Icons/page_add.png";
imgEnqTypeHeader.ToolTip = "New Letter Enquiry";
lblEnquiryTypeHeader.Text = "New Letter Enquiry";
break;
case EnquiryTypeDto.EnumEnquiryTypeDto.Telephone:
imgEnqTypeHeader.ImageUrl = "~/AMTImages/Icons/telephone_add.png";
imgEnqTypeHeader.ToolTip = "New Telephone Enquiry";
lblEnquiryTypeHeader.Text = "New Telephone Enquiry";
break;
case EnquiryTypeDto.EnumEnquiryTypeDto.InPerson:
imgEnqTypeHeader.ImageUrl = "~/AMTImages/Icons/comments_add.png";
imgEnqTypeHeader.ToolTip = "New In Person Enquiry";
lblEnquiryTypeHeader.Text = "New In Person Enquiry";
break;
case EnquiryTypeDto.EnumEnquiryTypeDto.MembersArea:
break;
case EnquiryTypeDto.EnumEnquiryTypeDto.MembersAdvisoryCentre:
imgEnqTypeHeader.ImageUrl = "~/AMTImages/Icons/building_add.png";
imgEnqTypeHeader.ToolTip = "New MAC Enquiry";
lblEnquiryTypeHeader.Text = "New MAC Enquiry";
break;
}
}
else
{
imgEnqTypeHeader.ClientVisible = false;
lblEnquiryTypeHeader.ClientVisible = false;
}
}
}
Session Manager.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using AMT2012.AmtService;
using AMT2012.RHS.Exchange.Service;
namespace AMT2014_Prototype.App_Code
{
public class SessionManager
{
#region Email Client session strings
public static string MailBoxFolder = "MailBoxFolder";
public static string MailBoxEmail = "MailBoxEmail";
public static string MailBoxMergedEmailConversationIds = "MailBoxMergedEmailConversationIds";
public static string MailBoxPreviousEmail = "MailBoxPreviousEmail";
public static string MailBoxEmailAttachmentUploaded = "MailBoxEmailAttachmentUploaded";
public static string MailBoxSearchString = "MailBoxSearchString";
public static string MailBoxSearch = "MailBoxSearch";
public static string MailBoxExpandedConversationId = "MailBoxExpandedConversationId";
public static string CacheRefresh = "CacheRefresh";
#endregion
public static string LoggedInUser = "LoggedInUser";
public static string ConfirmationPostCodeSearch = "ConfirmationPostCodeSearch";
#region ContactSearch
public static string ContactSearchResults = "ContactSearchResults";
public static string ContactSearchCriteria = "ContactSearchCriteria";
public static string PreviousSearchCriteria = "PreviousSearchCriteria";
public static string AddressSearchResults = "AddressSearchResults";
#endregion
#region KnowledgeBaseKeyword
public static string KnowledgeBaseKeyword = "KnowledgeBaseKeyword";
#endregion
#region Table Maintenance session strings
public static string SelectedTableId = "SelectedTableId";
public static string SelectedTableToEdit = "SelectedTableToEdit";
public static string CurrentKeywordRelations = "CurrentKeywordRelations";
public static string EditTableVisibility = "EditTableVisibility";
#endregion
#region User Maintenance
public static string Departments = "Departments";
public static string UploadedFileData = "UploadedFileData";
public static string UploadedFileName = "UploadedFileName";
public static string IsUserImageChanged = "IsUserImageChanged";
public static string NewUserEmailAddress = "NewUserEmailAddress";
public static string EditingUserDto = "EditingUserDto";
public static string EditUserVisibility = "EditUserVisibility";
public static string IsThemeChanged = "IsThemeChanged";
public static string CurrentTheme = "CurrentTheme";
#endregion
#region "News Content"
public static string EditingNewsItem = "EditingNewsItem";
public static string UploadedNewsImage = "UploadedNewsImage";
public static string UploadedNewsFileName = "UploadedNewsFileName";
public static string EditNewsItemVisibility = "EditNewsItemVisibility";
public static string IsNewsItemImageChanged = "IsNewsItemImageChanged";
#endregion
#region "Lock Maintenance"
public static string SectionLocks = "SectionLocks";
public static string EmailLocks = "EmailLocks";
public static string ResponseTextLocks = "ResponseTextLocks";
#endregion
#region "Paragraph Maintenance"
public static string SearchParagraphs = "SearchParagraphs";
public static string EditingParagraph = "EditingParagraph";
public static string SearchParagraphText = "SearchParagraphText";
public static string ParagrahSummaryVisibility = "ParagrahSummaryVisibility";
public static string SelectedDepartmentIdForKeyword = "SelectedDepartmentIdForKeyword";
public static string SelectedKeywordId = "SelectedKeywordId";
public static string SelectedKeyword = "SelectedKeyword";
public static string InsertingParagraph = "InsertingParagraph";
public static string LoadParagraphs = "LoadParagraphs";
public static string ParagraphViewerBtnVisibility = "ParagraphViewerBtnVisibility";
#endregion
#region "Hortifacts Maintenance"
public static string EditingHortifact = "EditingHortifact";
public static string HortifactSummaryVisibility = "HortifactSummaryVisibility";
public static string SearchHortifactText = "SearchHortifactText";
public static string SearchHortifacts = "SearchHortifacts";
public static string SelectedSubjectIdForTopics = "SelectedSubjectIdForTopics";
public static string SelectedTopicId = "SelectedTopicId";
public static string SelectedTopic = "SelectedTopic";
public static string AddHortifactAttachment = "AddHortifactAttachment";
public static string LoadHortifacts = "LoadHortifacts";
#endregion
#region "Leaflet Maintenance"
public static string ViewingLeafletId = "ViewingLeafletId";
public static string ReplacedLeafletData = "ReplacedLeafletData";
public static string ReplacedLeafletName = "ReplacedLeafletName";
public static string ReplacedLeafletFileExt = "ReplacedLeafletFileExt";
public static string IsLeafletReplaced = "IsLeafletReplaced";
public static string AddedLeafletData = "AddedLeafletData";
public static string AddedLeafletName = "AddedLeafletName";
public static string AddedLeafletFileExt = "AddedLeafletFileExt";
public static string LeafletSearchText = "LeafletSearchText";
public static string LeafletFilterByDeptId = "LeafletFilterByDeptId";
public static string SelectedLeafletsToAttach = "SelectedLeafletsToAttach";
public static string AttachedLeaflets = "AttachedLeaflets";
public static string UploadBatchLeaflet = "UploadBatchLeaflet";
public static string LeafletCallbackPanel = "LeafletCallbackPanel";
public static string Leaflets = "Leaflets";
#endregion
#region "Hortifact Attachment"
public static string ViewingHortifactId = "ViewingHortifactId";
public static string ViewingHortifactIdUnassociated = "ViewingHortifactIdUnassociated";
public static string ViewHortifactAttachmentId = "ViewHortifactAttachmentId";
public static string ViewHortifactAttachmentIdUnassociated = "ViewHortifactAttachmentIdUnassociated";
#endregion
#region "Web Links Viewer"
public static string WebLinks = "WebLinks";
public static string LoadWebLinks = "LoadWebLinks";
public static string PlantSelectorLink = "PlantSelectorLink";
public static string PlantSelectorSearchText = "PlantSelectorSearchText";
#endregion
#region "ACE Viewer"
public static string SelectedACESubjectIdForTopics = "SelectedACESubjectIdForTopics";
public static string SearchedACEDTO = "SearchedACEDTO";
public static string ACEWebLink = "ACEWebLink";
//public static string ACELinksAddedtoList = "ACELinksAddedtoList";
public static string iFrameHeight = "iFrameHeight";
#endregion
#region "Sticky Notes"
public static string Notes = "Notes";
public static string StickyNoteIndex = "StickyNoteIndex";
public static string EnquiryItemId = "EnquiryItemId";
#endregion
#region "Allocation"
public static string AllocatedDepartment = "AllocatedDepartment";
public static string AllocatedUser = "AllocatedUser";
#endregion
#region "KBKComboBox"
public static string SelectedKBK = "SelectedKBK";
public static string SelectedChildNodeCategory = "SelectedChildNodeCategory";
public static string SelectedKBKChildID = "SelectedKBKChildID";
public static string SelectedChildNodeCategoryValue = "SelectedChildNodeCategoryValue"; // Use on Select button click. Value = ChildID(for leaflet & weblink), text for others
#endregion
#region "KBKComboBoxGridLookUp"
public static string SelectedCategoryValue = "SelectedCategoryValue"; // Use on Select button click. Value = ChildID(for leaflet & weblink), text for others
public static string SelectedCategory = "SelectedCategory";
public static string SearchKBK = "SearchKBK"; // Contains the responsetext
public static string KbkDisplay = "KbkDisplay";
public static string KbkGridAutoFilterText = "KbkGridAutoFilterText";
#endregion
#region "Monitors"
public static string FirstResolvedEnquiryIdOnTop = "FirstResolvedEnquiryIdOnTop"; // For top most enquiry id in grid monitor to be kept open on page load
public static string FirstCompletedEnquiryIdOnTop = "FirstCompletedEnquiryIdOnTop"; // For top most enquiry id in grid monitor to be kept open on page load
public static string FirstLoggedEnquiryIdOnTop = "FirstLoggedEnquiryIdOnTop"; // For top most enquiry id in grid monitor to be kept open on page load
public static string SentResponses = "SentResponses";
public static string LoggedEnquiries = "LoggedEnquiries";
public static string CompletedEnquiries = "CompletedEnquiries";
public static string SystemCompletedEnquiries = "SystemCompletedEnquiries";
#endregion
#region WeblinksHistory
public static string BackHistoryBucket = "BackHistoryBucket";
public static string CurrentlyDisplayedWebLink = "CurrentlyDisplayedWebLink";
public static string ForwardHistoryBucket = "ForwardHistoryBucket";
#endregion
#region "System Settings"
public static string ArchiveSettings = "ArchiveSettings";
public static string MembersAreaEnqAllocation = "MembersAreaEnqAllocation";
#endregion
#region "Enquiry"
public static string EnquiryPersonId = "EnquiryPersonId";
public static string NewEnquiryType = "NewEnquiryType";
public static string NewEnquiryContactType = "NewEnquiryContactType";
public static string NewEnquiryObject = "NewEnquiryObject";
public static string CurrentNewSection = "CurrentNewSection";
public static string EmailIdsOfCurrentEnquirer = "EmailIdsOfCurrentEnquirer";
public static string EmailIdsForChangeResponseFormat = "EmailIdsForChangeResponseFormat";
public static string LoadingEnquiryItemId = "LoadingEnquiryItemId";
public static string LoadingEnquiryNumber = "LoadingEnquiryNumber";
public static string LoadingEnquiryDetails = "LoadingEnquiryDetails";
public static string CurrentSavedSection = "CurrentSavedSection";
public static string SelectedCategoryType = "SelectedCategoryType";
public static string EnquiryEntryPointUrl = "EnquiryEntryPointUrl";
public static string ExistingEnqNewSection = "ExistingEnqNewSection";
#endregion
#region "Enquiry BreadCrumb"
public static string FinishedStepNumber = "FinishedStepNumber";
#endregion
public static string SelectedSupportTicketId = "SelectedSupportTicketId";
public static string SelectedSupportTicketRecordVersion = "SelectedSupportTicketRecordVersion";
public static string LoadedPlantNames = "LoadedPlantNames";
public static string SelectedSubjectId = "SelectedSubjectId";
public static UserDto GetCurrentUser()
{
return GetSession(LoggedInUser) as UserDto;
}
public static object SetSession(string sessionString, object obj)
{
HttpContext.Current.Session[sessionString] = obj;
return obj;
}
public static object GetSession(string sessionString)
{
if (HttpContext.Current == null)
{
return null;
}
return HttpContext.Current.Session[sessionString];
}
public static void UpdateEmail(EmailDto email)
{
var mail = (EmailDto)GetSession(MailBoxEmail);
mail = email;
SetSession(MailBoxEmail, mail);
}
public static LoginDto Login = new LoginDto
{
Username = ConfigurationManager.AppSettings["AMTUser"],
Password = ConfigurationManager.AppSettings["AMTPassword"]
};
public static SoaLicenceDto SoaLicenceDto = new SoaLicenceDto
{
CallerId = ConfigurationManager.AppSettings["SoaLicenceCallerId"],
LicenceKey = ConfigurationManager.AppSettings["SoaLicenceCallerPassword"]
};
public static void ClearEnquirySessions(bool clearContactSession)
{
// this baby clears down all enquiry related sessions.
SetSession(MailBoxSearch, null);
SetSession(MailBoxEmail, null);
SetSession(MailBoxMergedEmailConversationIds, null);
SetSession(MailBoxEmailAttachmentUploaded, null);
SetSession(MailBoxExpandedConversationId, null);
SetSession(MailBoxFolder, null);
SetSession(MailBoxSearchString, null);
if (clearContactSession)
{
SetSession(EnquiryPersonId, null);
SetSession(NewEnquiryContactType, null);
}
SetSession(ContactSearchResults, null);
// SetSession(EnquiryItemId, null);
// SetSession(NewEnquiryType, null);
// SetSession(EnquiryEntryPointUrl, null);
// SetSession(FirstCompletedEnquiryIdOnTop, null);
// SetSession(FirstLoggedEnquiryIdOnTop, null);
// SetSession(FirstResolvedEnquiryIdOnTop, null);
// SetSession(NewEnquiryObject, null);
SetSession(NewEnquiryObject, null);
SetSession(NewEnquiryType, null);
SetSession(CurrentNewSection, null);
SetSession(AllocatedDepartment, null);
SetSession(AllocatedUser, null);
SetSession(SelectedLeafletsToAttach, null);
SetSession(SelectedKBK, null);
// SetSession(LoadingEnquiryDetails, null);
// SetSession(LoadingEnquiryNumber, null);
// SetSession(LoadingEnquiryItemId, null);
SetSession(FinishedStepNumber, 0);
}
public static void ClearSessionsBeforeCreatingNewEnquiry()
{
SetSession(EnquiryItemId, null);
SetSession(FirstCompletedEnquiryIdOnTop, null);
SetSession(FirstLoggedEnquiryIdOnTop, null);
SetSession(FirstResolvedEnquiryIdOnTop, null);
SetSession(NewEnquiryObject, null);
SetSession(LoadingEnquiryDetails, null);
SetSession(LoadingEnquiryNumber, null);
SetSession(LoadingEnquiryItemId, null);
SetSession(CurrentSavedSection, null);
}
}
}
My problem is that in my controller it says:
Cannot resolve symbol 'App_Code'
and
Cannot resolve symbol 'SessionManager'
See screenshots for how it looks in the IDE.

App_Code is a special folder in ASP.Net which is interfering with your namespace. Use a different name and it will work.
See this link: http://msdn.microsoft.com/en-us/library/vstudio/t990ks23(v=vs.100).aspx

For some reason, MVC doesn't like App_Code folder in the project. I used a different name and it worked.

Related

Select value from string

I have this code that is telling a system to open the tab "Employee" in a WPF client.
class Startup
{
public void Init()
{
var screen = Tabs.Employee;
Tabs.OpenTab(screen, null);
}
}
What I would like to do is something like this:
string screenName = "Employee";
var screen = Tabs.screenName;
In order to be able to pass the Employee as a value.
The Tabs class looks like this:
public class Tabs
{
public delegate void AddDockTab(string controlName, object argument = null);
public const string Empty = "Empty";
public const string Employee = "Employee";
public const string Customer = "Customer";
private static UnicontaTabs utab;
public static event AddDockTab OnAddDockTab;
protected Tabs()
{
utab = this;
}
public static void OpenTab(string controlName, object argument)
{
if (utab != null)
{
utab.AddTab(controlName, argument);
}
}
protected virtual void AddTab(string controlName, object argument)
{
Tabs.OnAddDockTab?.Invoke(controlName, argument);
}
public static IEnumerable<string> GetControlNames()
{
FieldInfo[] fields = typeof(Tabs).GetFields(BindingFlags.Static | BindingFlags.Public);
return fields.Select((FieldInfo f) => f.Name);
}
}

Dialog flow chat bot token expires every 5 minutes

I have been working on a project with unity about chat bots using dialog flow,
the problem I am facing is as follows: I have to run some commands in order to retrieve the token from google in terminal then a C# script uses this token to run some functions but the problem is that the token expires every 5 minutes since I m consuming the API so is there a way to automate the process in a bash script file where It can run the commands and get the token then it is directly used in the C# script.
accessing agent
Getting the token
DialogflowAPIScript
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Networking;
using JsonData;
public class DialogflowAPIScript : MonoBehaviour
{
void Start()
{
i0tBjGc2WlRT9GePIqe1_j5Xq9flXHMGJWnn5sEjNHyG1VfMFqtt3WapHAVo2-RwvPNKRTHI0BkF9OVUzZJ5OWJEILr64_ge1tgcbS7AA"));
StartCoroutine(PostRequest("https://dialogflow.googleapis.com/v2/projects/newagent-taqyfj/agent/sessions/34563:detectIntent",
"ya29.c.Ko4B0AeMSB_eB-0DumT7ubxKoJc47TMOKhgls589I-F8whsTbnZvAgFn6Ft-sqwcFPI1n_-CQIp4zk-e3Ip9lVvXvrJFOfPmoejayJhjHR9Gu36XsulR71_iHGnvb8m4aYbkBF9tnkA05cJahNyVZoK5SWR3EgAb4XofkMfp7Qt8vtnMa6J-Q89YZevUk3VfaA"));
}
void Update()
{
}
IEnumerator PostRequest(String url, String AccessToken)
{
UnityWebRequest postRequest = new UnityWebRequest(url, "POST");
RequestBody requestBody = new RequestBody();
requestBody.queryInput = new QueryInput();
requestBody.queryInput.text = new TextInput();
requestBody.queryInput.text.text = "hello";
requestBody.queryInput.text.languageCode = "en";
string jsonRequestBody = JsonUtility.ToJson(requestBody, true);
Debug.Log(jsonRequestBody);
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonRequestBody);
postRequest.SetRequestHeader("Authorization", "Bearer " + AccessToken);
postRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
postRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
//postRequest.SetRequestHeader("Content-Type", "application/json");
yield return postRequest.SendWebRequest();
if (postRequest.isNetworkError || postRequest.isHttpError)
{
Debug.Log(postRequest.responseCode);
Debug.Log(postRequest.error);
}
else
{
Debug.Log("Response: " + postRequest.downloadHandler.text);
byte[] resultbyte = postRequest.downloadHandler.data;
string result = System.Text.Encoding.UTF8.GetString(resultbyte);
ResponseBody content = (ResponseBody)JsonUtility.FromJson<ResponseBody>(result);
Debug.Log(content.queryResult.fulfillmentText);
}
}
IEnumerator GetAgent(String AccessToken)
{
UnityWebRequest www = UnityWebRequest.Get("https://dialogflow.googleapis.com/v2/projects/newagent-taqyfj/agent");
www.SetRequestHeader("Authorization", "Bearer " + AccessToken);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
byte[] results = www.downloadHandler.data;
}
}
}
request RequestBody
using System.Collections.Generic;
namespace JsonData
{
v2/rest/v2/projects.agent.sessions/detectIntent#QueryParameters
public class RequestBody
{
public QueryInput queryInput;
public string inputAudio;
}
public class QueryInput
{
public TextInput text;
//public InputAudioConfig audioConfig;
}
public class InputAudioConfig
{
public AudioEncoding audioEncoding;
public int sampleRateHertz;
public String languageCode;
public String[] phraseHints;
}
public enum AudioEncoding
{
AUDIO_ENCODING_UNSPECIFIED,
AUDIO_ENCODING_LINEAR_16,
AUDIO_ENCODING_FLAC,
AUDIO_ENCODING_MULAW,
AUDIO_ENCODING_AMR,
AUDIO_ENCODING_AMR_WB,
AUDIO_ENCODING_OGG_OPUS,
AUDIO_ENCODING_SPEEX_WITH_HEADER_BYTE
}
public enum WebhookState
{
STATE_UNSPECIFIED,
WEBHOOK_STATE_ENABLED,
WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING
}
public class ResponseBody
{
public string responseId;
public QueryResult queryResult;
public Status webhookStatus;
}
public class QueryResult
{
public string queryText;
public string languageCode;
public int speechRecognitionConfidence;
public string action;
public Struct parameters;
public bool allRequiredParamsPresent;
public string fulfillmentText;
public Message[] fulfillmentMessages;
public string webhookSource;
public Struct webhookPayload;
public Context[] outputContexts;
public Intent intent;
public int intentDetectionConfidence;
public Struct diagnosticInfo;
}
[Serializable]
public class Status
{
public int code;
public string message;
public Object[] details;
}
[Serializable]
public class Intent
{
public string name;
public string displayName;
public WebhookState webhookState;
public int priority;
public bool isFallback;
}
public class Context
{
public string name;
}
public class Struct
{
public Dictionary<string, Value> fields;
}
public class Value
{
public NullValue null_value;
public double number_value;
public string string_value;
public bool bool_value;
public Struct struct_value;
public ListValue list_value;
public void ForBool(bool value){
this.bool_value = value;
}
public void ForString(string value)
{
this.string_value = value;
}
public void ForNumber(double number){
this.number_value = number;
}
public void ForNull()
{
this.null_value = NullValue.null_vaule;
}
public void ForStruct(Struct value){
this.struct_value = value;
}
public void ForList(ListValue value){
this.list_value = value;
}
}
public enum NullValue
{
null_vaule
}
public class ListValue{
public Value values;
}
public class Text{
public string[] text;
}
[Serializable]
public class Message{
public Text text;
}
}```

Set value of a static variable using a function

I have declared some static variables in my solution as below,
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = "M23";
public static string ApproverlevelL2 = "Cre";
public static string ApproverlevelL3 = "Free34";
public static string ApproverlevelL4 = "CDF";
public static string ApproverlevelL5 = "FM";
}
}
My question is, If i try to set it the like below then i get the error as :
An object reference is required for the non-static field, method, or
property
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
}
}
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
So how can i achieve this?
Looks like you are trying to call an instance method (non-static) from a static property.
Try making your method static:
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
Do you mean this:
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
private static string getLevel(string levelID)
{
string levelName;
logic here
return levelName;
}
}
}
If your issue is that you want the getLevel method to be in a different class, you could add a Function into your static class and override it with the method.
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static Func<string, string> getLevel = x => string.Empty;
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
public class WhateverClass
{
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// call this before accessing the fields in your Constants class
public void Init()
{
Constants.getLevel = x => getLevel(x);
}
}
}
The only reason I can think of to do this is maybe you have two applications using this static class and they need to get the level differently. Maybe one uses actual constant values and another reads a database, etc.
If you don't require this then the simplest answer is to actually put the method into the class as a static method:
namespace SSPWAS.Utilities
{
public class Constants
{
public static string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
}
Your "constants" are not constant. Make them readonly if you want them to behave like constants while making use of initialising static members with values. You could also make them properties and use just the get accessor to call the getLevel method.
As others have pointed out you cannot call a non-static member from within a static member, without instantiating an instance of the non-static class.
Your getLevel method also needs to be in its own class. As it stands it doesn't belong to a class or namespace. If you want it in its own separate class then just set the method to static.
.NET naming conventions recommend you use Pascal Casing for methods. So rename your getLevel method.
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = GetLevel("1"),
ApproverlevelL2 = GetLevel("2"),
ApproverlevelL3 = GetLevel("3"),
ApproverlevelL4 = GetLevel("4"),
ApproverlevelL5 = GetLevel("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => GetLevel("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return GetLevel("7"); } }
private static string GetLevel(string levelId)
{
//... do logic
return "";
}
}
}
Or if you want the method in its own class:
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = Level.Get("1"),
ApproverlevelL2 = Level.Get("2"),
ApproverlevelL3 = Level.Get("3"),
ApproverlevelL4 = Level.Get("4"),
ApproverlevelL5 = Level.Get("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => Level.Get("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return Level.Get("7"); } }
}
public class Level
{
public static string Get(string levelId)
{
//... do logic
return "";
}
}

C# json deserialize to (this) inside object

I am trying to get an object to deserialize into itself. I have tride the following:-
public class JobID
{
public string jobname;
public string first;
public string second;
public string third;
public string clientName;
public string workflow;
}
public void load(string fname)
{
string s = File.ReadAllText(fname);
this = JsonConvert.DeserializeObject<JobID>(s);
}
But the word this is 'read only' according to the error I get.
I have used 'this.jobname = "X";' before so clearly 'this' is not read only.
I am using Newtonsof.Json.
Why not use static method to load the object. Such as :
public class JobID
{
public string jobname;
public string first;
public string second;
public string third;
public string clientName;
public string workflow;
public static JobId Load(string fname){
string s = File.ReadAllText(fname);
return JsonConvert.DeserializeObject<JobID>(s);
}
}
Although you can assign a value to a property of 'this', you can't change the object to which 'this' refers to.
The 'this' keyword refers to the current object instance in the context (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/this).
Assuming the Load function is inside another object (or static), you could do something like:
public class JobID
{
public string jobname;
public string first;
public string second;
public string third;
public string clientName;
public string workflow;
}
public class JobReader
{
// Property to store deserialized object
public JobID Job { get; set; }
public void load(string fname)
{
string s = File.ReadAllText(fname);
// Assign object to property.
this.JobID = JsonConvert.DeserializeObject<JobID>(s);
}
}
You can use the static method as suggested by Xbotter to create a new instance. But for some reason if you want to deserialize the file content into current object only, then easiest way would be:
public class JobID
{
public string jobname;
public string first;
public string second;
public string third;
public string clientName;
public string workflow;
public void load(string fname)
{
string s = File.ReadAllText(fname);
JobID tmp = JsonConvert.DeserializeObject<JobID>(s);
copy(tmp);
}
public void copy(JobID tmp)
{
this.jobname = tmp.jobname;
// do the same for other properties that you want to copy
}
}
If you want to do this without a static method, you can use the JsonSerializer.Populate method. Example code:
public class JobID
{
public string jobname;
public string first;
public string second;
public string third;
public string clientName;
public string workflow;
public void load(string fname)
{
string s = File.ReadAllText(fname);
new JsonSerializer().Populate(new JsonTextReader(new StringReader(s)), this);
}
}
Anssssss provided the answer I've been looking for years. Thank you!
This is how I used it:
bool bOk = false;
StreamReader myFileStream = null;
Newtonsoft.Json.JsonSerializer mySerializer = new Newtonsoft.Json.JsonSerializer();
try
{
myFileStream = File.OpenText(sFilePath);
mySerializer.Populate(myFileStream, this);
bOk = true;
}
catch (Exception e)
{
string sException = e.ToString();
CHelper.ThrowException(new Exception(sException + "\n\n" + sFilePath));
}
finally
{
if (myFileStream != null)
{
myFileStream.Close();
}
}
return bOk;

T4 template to generate relative path of solution files

I need a T4 template or something else to integrate with Visual studio to generate relative path of files in solution.
Is their any add-ins or t4 to this?
I'm working with Visual studio 2012.
something like this:
public static class Scripts
{
public static class AdminSkin
{
public static class Css
{
public const string Site = "/Scripts/adminskin/css/site.css";
public const string SiteFa = "/Scripts/adminskin/css/site-fa.css";
public const string Reset = "/Scripts/adminskin/css/reset.css";
public const string SimpleList = "/Scripts/adminskin/css/simple-lists.css";
public const string SpecialPages = "/Scripts/adminskin/css/special-pages.css";
}
public static class Js
{
public const string Site = "/Scripts/adminskin/js/site.js";
public const string JqueryaccessibleList = "/Scripts/adminskin/js/jquery.accessibleList.js";
public const string Jquerytip = "/Scripts/adminskin/js/jquery.tip.js";
public const string List = "/Scripts/adminskin/js/list.js";
public const string Oldbrowsers = "/Scripts/adminskin/js/old-browsers.js";
public const string LiveControl = "/Scripts/adminskin/js/live-control.js";
}
}
public static class Calendar
{
public static class Js
{
public const string Calendar = "/Scripts/calendar/calendar.js";
public const string CalendarSetup = "/Scripts/calendar/calendar-setup.js";
public const string CalendarFa = "/Scripts/calendar/calendar-fa.js";
public const string CalendarEn = "/Scripts/calendar/calendar-en.js";
}
public static class Css
{
public const string Theme = "/Scripts/calendar/aqua/theme.css";
}
}
public static class HighChart
{
public static class Js
{
public const string Highstock = "/Scripts/highchart/highstock.js";
public const string HighstockModified = "/Scripts/highchart/highstock.src.js";
public const string Theme = "/Scripts/highchart/themes/mytheme.js";
public const string Exporting = "/Scripts/highchart/modules/exporting.src.js";
}
}
public static class ImageGallery
{
public static class Js
{
public const string JqueryEasing = "/Scripts/ImageGallery/js/jquery.easing.1.3.min.js";
public const string JqueryWtRotator = "/Scripts/ImageGallery/js/jquery.wt-rotator.min.js";
public const string Preview = "/Scripts/ImageGallery/js/preview.js";
}
public static class Css
{
public const string Preview = "/Scripts/ImageGallery/preview.css";
public const string JqueryWtRotator = "/Scripts/ImageGallery/wt-rotator.css";
}
}
public static class JQuery
{
public static class Js
{
public const string JqueryCdn = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js ";
public const string JqueryUiCdn = "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.20/jquery-ui.min.js";
public const string JqueryUiCssCdn = "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.20/themes/ui-lightness/jquery-ui.css";
public const string JqueryLocal = "/Scripts/jquery/jquery-1.7.min.js";
public const string JqueryUiLocal = "/Scripts/jquery-ui/js/jquery-ui-1.8.20.custom.min.js";
public const string JqueryUiCssLocal = "/Scripts/jquery-ui/css/ui-lightness/jquery-ui-1.8.20.custom.css";
}
}
public static class Linq
{
public static class Js
{
public const string Linq = "/Scripts/linq.js/linq.min.js";
}
}
public static class Moment
{
public static class Js
{
public const string Moment = "/Scripts/moment/moment.min.js";
}
}
public static class Lang
{
public static class Js
{
public const string Jalali = "/Scripts/lang/jalali.js";
public const string LangFa = "/Scripts/lang/lang-fa.js";
}
}
}
T4MVC might be what you are looking for. It is a T4 template for ASP.NET MVC apps that will create strongly typed helpers. It will generate a set of classes that you can use instead of using strings. For static files such as javascript files there will be a set of classes such as:
Links.Scripts.jquery_validate_js
This will return a string of the form "~/Scripts/jquery.validate.js".
For a WebForms project David Ebbo created a simple T4 template called AspPathGuru.tt. This currently only supports .aspx, .ascx and .master files. However if you edit the IgnoreFile method, as shown below, you can generate code for other files:
bool IgnoreFile(FileInfo file) {
// Only look for a few specific extensions
switch (file.Extension.ToLowerInvariant()) {
case ".aspx":
case ".ascx":
case ".js":
case ".css":
case ".master":
return false;
}
return true;
}
This will generate a Paths class you can use as shown below:
Paths.Scripts.jquery_1_4_1_js

Categories