I have static class with conts inside:
static class RestfulPaths {
static string BASE_URL = "A";
static string SYNC_CHECK = "A";
}
In another class I try to get const as:
RestfulPaths.BASE_URL
Make your class and its properties also public, then you'll get them from the other class.
public static class RestfulPaths
{
public static string BASE_URL = "A";
public static string SYNC_CHECK = "A";
}
public static class RestfulPaths {
public static string BASE_URL = "A";
public static string SYNC_CHECK = "A";
}
Related
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 "";
}
}
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.
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
I want to find elegant solution for defs class in C# Example:
Instead of:
class Class1
{
public static readonly string length = "length_Class1";
public static readonly string height = "height_Class1";
public static readonly string width = "width_Class1";
}
class Class2
{
public static readonly string length = "length_Class2";
public static readonly string height = "height_Class2";
public static readonly string width = "width_Class2";
}
Create template class. I thought of the following solution but it looks not so elegant:
internal abstract class AClass
{
}
internal class Class1 : AClass
{
}
internal class Class2 : AClass
{
}
class Class1<T> where T : AClass
{
public static readonly string length = "length_" + typeof(T).Name;
public static readonly string height = "height_" + typeof(T).Name;
public static readonly string width = "width_" + typeof(T).Name;
}
EDIT:
I have a lot of parameter names that I get/set from external data source, I would like to have two Instances of Defs for that. Length , Weight, Height are only for Illustration, there are a lot more.
EDIT:
I chose Generics because I think that there is a way to make the concatination in compile time (like in c++). Is it possible to do that?
Could you help me with more elegant solution?
Thanks!!!
It seems to me that you don't actually need the properties to be static, or the class to be generic. So, you can do something like:
class ParameterNames
{
public string Length { get; private set; }
public string Height { get; private set; }
public string Width { get; private set; }
public ParameterNames(string className)
{
Length = "length_" + className;
Height = "height_" + className;
Width = "width_" + className;
}
}
Although you might want to refactor your code, so that the code that accesses the external resource doesn't need to deal with those parameter names at all:
abstract class ExternalResource
{
private readonly string m_className;
protected ExternalResource(string classname)
{
m_className = className;
}
protected object GetParameterValue(string name)
{
string fullName = name + '_' + m_className;
// actually access the resource using fullName
}
}
public class SpecificParameters : ExternalResource
{
public SpecificParameters(string className)
: base(className)
{ }
public int Length { get { return (int)GetParameterValue("length"); } }
…
}
Doing this wouldn't avoid concatenating strings repeatedly, but I'm not sure why you want to avoid that, doing that should be pretty fast.
How can I access a variable in one public class from another public class in C#?
I have:
public class Variables
{
static string name = "";
}
I need to call it from:
public class Main
{
}
I am working in a Console App.
That would just be:
Console.WriteLine(Variables.name);
and it needs to be public also:
public class Variables
{
public static string name = "";
}
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
You need to specify an access modifier for your variable. In this case you want it public.
public class Variables
{
public static string name = "";
}
After this you can use the variable like this.
Variables.name
class Program
{
Variable va = new Variable();
static void Main(string[] args)
{
va.name = "Stackoverflow";
}
}