Using C# with ASP.NET on an Intranet website. I've got multiple "Admin" pages where I'm checking fields to make sure a date is present, checking fields to make sure the Username is present and filling in those fields if they were left blank. On all of these pages, there exists fields with identical names. The block of code I'm using in the code-behind is below:
//If the User fields are empty, set them to the current user
string ActiveUser = System.Web.HttpContext.Current.User.Identity.Name;
string LoginID = ActiveUser.Right(6);
var txtLoadedBy_chk = string.IsNullOrEmpty(str5);
if ((txtLoadedBy_chk == true))
{
str5 = LoginID;
}
var txtUpdatedBy_chk = string.IsNullOrEmpty(str7);
if ((txtUpdatedBy_chk == true))
{
str7 = LoginID;
}
var txtFlgUpdatedBy_chk = string.IsNullOrEmpty(str9);
if ((txtFlgUpdatedBy_chk == true))
{
str9 = LoginID;
}
// If the date fields are NULL, set them to today's date
var txtLoadedOn_chk2 = string.IsNullOrEmpty(str6);
if ((txtLoadedOn_chk2 == true))
{
str6 = DateTime.Today.ToString();
}
var txtUpdatedOn_chk2 = string.IsNullOrEmpty(str8);
if ((txtUpdatedOn_chk2 == true))
{
str8 = DateTime.Today.ToString();
}
var txtFlgUpdatedOn_chk2 = string.IsNullOrEmpty(str10);
if ((txtFlgUpdatedOn_chk2 == true))
{
str10 = DateTime.Today.ToString();
}
// Check to make sure the dates entered are valid. If not, let the user know and
// then exit out of the code so the record is not saved
var txtLoadedOn_chk = DateTimeHelpers.IsValidSqlDateTimeNative(str6);
var txtUpdatedOn_chk = DateTimeHelpers.IsValidSqlDateTimeNative(str8);
var txtFlgUpdatedOn_chk = DateTimeHelpers.IsValidSqlDateTimeNative(str10);
if ((txtLoadedOn_chk == false) || (txtUpdatedOn_chk == false) || (txtFlgUpdatedOn_chk == false))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "<script>alert('WARNING !! One of your date fields is invalid')</script>");
return;
}
I'm thinking that since I do the EXACT same checks on all of these forms, I should be able to put this block of code somewhere and just reference it, instead of putting it in every form. How would I go about doing that? If I put it in a separate page or CS file, how will it know which form is calling it so it reads the proper fields? If you can provide some sample code, that would be a huge help. TIA!
Oh, and DateTimeHelpers is a class I created, in case you're wondering.
EDIT: I just want to be clear on something; this code is in the code-behind and is called when the user presses the "Save" button. It's just verifying the data before it tries to write it to the SQL Server table.
What you want to do here is create a user control. You can add one of those to your project with the "New File" stuff Visual Studio provides. I will call that user control Fields.ascx in this answer.
The code in your answer goes in the code-behind for that user control (Fields.ascx.cs). The form elements that you have on every page go in Fields.ascx.
Once you do that, you reference the user control at the top of your page like this:
<%# Register TagPrefix="user2174085" TagName="MyFields" Src="~/Path/To/Fields.ascx" %>
And then you add the fields to your page in the right place with the following code:
<user2174085:MyFields runat="server" />
In the <%# Register %> portion, you can make the TagPrefix and TagName pretty much anything you want, just make sure they match when you use the control.
You could always write a public method in a cs file and pass your controls as reference variables. Here is a quick example of what that could look like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace mol_intranet
{
public class ClassTesting
{
//pass the fields to be checked/updated here as ref variables
public void checkFields(ref TextBox loadedby, ref TextBox updatedby)
{
string ActiveUser = System.Web.HttpContext.Current.User.Identity.Name;
string LoginID = ActiveUser.Right(6);
var txtLoadedBy_chk = string.IsNullOrEmpty(loadedby.Text);
if ((txtLoadedBy_chk == true))
{
loadedby.Text = LoginID;
}
var txtUpdatedBy_chk = string.IsNullOrEmpty(updatedby.Text);
if ((txtUpdatedBy_chk == true))
{
updatedby.Text = LoginID;
}
}
}
}
Then just call the method in your code and pass your controls:
ClassTesting t = new ClassTesting();
t.checkFields(txtLoadedBy, txtUpdatedBy);
Hope this helps.
Related
I have this requirment to only index that data, for searching, which is being used in some page. For example if I upload a document it shouldn't be available for search until I use it in some page. I found out this code online
ContentIndexer.Instance.Conventions.ForInstancesOf().ShouldIndex(x =>
{
var contentRepository =
EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance();
var contentSoftLinkRepository =
EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance();
var softLinks = contentSoftLinkRepository.Load(x.ContentLink, true);
try
{
foreach (var softLink in softLinks)
{
if (softLink.SoftLinkType == ReferenceType.ExternalReference ||
softLink.SoftLinkType == ReferenceType.ImageReference)
{
var content =
contentRepository.Get(softLink.OwnerContentLink);
if (!ContentIndexer.Instance.Conventions.ShouldIndexConvention.ShouldIndex(content).Value) // don't index referenced file if content is marked as not indexed
{
continue;
}
// only index if content is published
var publicationStatus =
content.PublishedInLanguage()[softLink.OwnerLanguage.Name];
if (publicationStatus != null &&
(publicationStatus.StartPublish == null ||
publicationStatus.StartPublish < DateTime.Now) &&
(publicationStatus.StopPublish == null ||
DateTime.Now < publicationStatus.StopPublish))
{
return true;
}
}
}
}
catch
{
// ooops something went wrong. Better not index this one ;-)
}
return false;
});
This works when I attach softlinks. But lets say a page has a property called Content type and when I add something in there, lets say a block which has softlinks to that document, it doesn't work. I am stuck in there. Any hints?
Do you have a wildcard * host configured on any of your sites?
Check Admin > Manage websites and go through all sites to see if there is a * configured.
Having a wildcard tells Episerver Find to index standalone content (i.e. globalassets) using the site primary URL that contains the wildcard, regardless of it being referenced. If you don't have a wildcard configured, Episerver Find can't index content that are NOT referenced (i.e. globalassets) because it cannot generate a public URL for it. Global assets that are referenced will be indexed using the domain of the site that references it. Hope this helps.
I am electing to do session to store a value that I will need to call and update throughout a handful of controllers and views. I know it is possible to do something like this with a BaseViewModel.cs, or something less session-y, but I am trying to see how Session can possibly solve my needs. That out of the way, here is what I am doing:
Flow
I have a partial view that is rendered on my _layout page like so:
#Html.Action("OrgSwitch", new { controller = "Common", area = "InkScroll" })
This is a drop down list containing a logged in users organizations. It hits a CommonController that takes care of things like rendering model-bound logic on layout pages. In the CommonController I have this view and a postback, like so:
[ChildActionOnly]
public ViewResult OrgSwitch()
{
var userOrgs = new List<SelectListItem>();
var user = Ctx.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
int key = 0;
if (user.Organizations.Count > 0)
{
TempData["HasOrgs"] = true;
foreach (var org in user.Organizations)
{
if (Session["SelectedOrgKey"] == null)
{
//currently setting selected by primary org id
//todo: set selected to tempdata selectedOrgId if there is one.
userOrgs.Add(org.OrganizationId.ToString() == user.PrimaryOrgId
? new SelectListItem { Text = org.Name, Value = org.OrganizationId.ToString(), Selected = true }
: new SelectListItem { Text = org.Name, Value = org.OrganizationId.ToString(), Selected = false });
}
else
{
key = Convert.ToInt32(Session["SelectedOrgKey"]);
userOrgs.Add(org.OrganizationId == key
? new SelectListItem { Text = org.Name, Value = org.OrganizationId.ToString(), Selected = true }
: new SelectListItem { Text = org.Name, Value = org.OrganizationId.ToString(), Selected = false });
}
}
ViewBag.UserOrgs = userOrgs.OrderBy(x => x.Text);
}
else
{
ViewBag.UserOrgs = userOrgs;
TempData["HasOrgs"] = false;
}
Session["SelectedOrgKey"] = key;
return View();
}
[HttpPost]
public RedirectToRouteResult OrgSwitch(string UserOrgs)
{
Session["SelectedOrgKey"] = UserOrgs;
return RedirectToAction("Index", "Recruiter", new { orgId = UserOrgs, area = "InkScroll" });
}
This more or less on initial load will render the drop down list and default it to the users primary org. If they select something and post back that selection, it will display the selected one by default on subsequent pages.
attempt and failure
I am trying various ways of utilizing the Session value. One area in a viewresult:
[ChildActionOnly]
public ViewResult StaffList()
{
var user = Ctx.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
var model = new List<StaffListViewModel>();
int key = Convert.ToInt32(Session["SelectedOrgKey"]);
var org = user.Organizations.FirstOrDefault(x => x.OrganizationId == key);
if (org.RegisteredMembers != null)
{
foreach (var req in org.RegisteredMembers)
{
model.Add(new StaffListViewModel
{
UserName = req.UserName,
Name = (req.FirstName ?? "") + " " + (req.LastName ?? ""),
ImageLocation = req.ImageLocation
});
}
}
Session["SelectedOrgKey"] = key;
return View(model);
}
in here 'key' is coming up empty.
Another try is putting it in the layout cshtml file like so:
<li><a href="#Url.Action("Staff", "Recruiter", new {area="",
orgId = Convert.ToInt32(Session["SelectedOrgId"])})">Staff</a></li>
in this one if I hover over the link, the orgId is always equal to 0. Am I messing this up somewhere? Really, I need to have this SelectedOrgId available to any page on the application.
An answer for posterity sake:
The code in the question DOES work. The way I am setting and calling session in asp.net mvc works fine. If you have arrived here in a vain search to get session working, then keep looking I guess. The issue I was have related to my control flow and the parameter i was passing in. Once I removed the 'orgId' from the parameters above, I refactored the if/else stuff to just look at session. So the issue was that somewhere in the app I am working on, orgId was not being changed from '0'. Anyway, I am an idiot, but at least I can give you a quick overview of what the hell Session is in asp.net mvc and how easy it is to use:
Setting up app to use session
Session is defaulted to be in process with a timeout of 20 minutes. If you feel like something is overwriting that default you can set it explicitly in your web.config (root web.config on a standard asp.net mvc app):
<system.web>
<sessionState mode="InProc" timeout="60"></sessionState>
...other stuff..
</system.web>
I set my timeout above to 60 minutes since I wanted it to stay around a little longer. Standard is 20.
Setting a session variable
Pretty damn simple. Do this:
Session["MyStringVariable"] = "Some value I want to keep around";
Session["MyIntegerVariable"] = 42;
Retrieving the session variable
again, pretty simple, you just need to pay attention to casting/converting the variable to what suits you.
var localVar = Session["MyStringVariable"].ToString();
var anotherLocalVar = Convert.ToInt32(Session["MyIntegerVariable"] = 42);
So, yeah, I was doing it right, but due to other complexities in my code above, I blamed the big bad Session and not my brain.
Hope this helps someone! (And if I have the above info wrong, please let me know and I will update!).
I have some trouble to select the targeted acadObject. I get the input via selectionset.SelectonScreen method.
Here i can get more number of object from modelspace based on my filter condition.But i need only one object from the user.
Here i mentioned my code below:
AcadSelectionSet selset= null;
selset=currDoc.selectionset.add("Selset");
short[] ftype=new short[1];
object[] fdata=new object[1];
ftype[0]=2;//for select the blockreference
fdata[0]=blkname;
selset.selectOnScreen ftype,fdata; // Here i can select any no. of blocks according to filter value but i need only one block reference.
Please help me to solve this problem.
That's possible using other Autocad .NET libraries (instead of Interop library). But fortunately, one does not exclude the other.
You will need to reference the libraries containing the following namespaces:
using Autodesk.Autocad.ApplicationServices
using Autodesk.Autocad.EditorInput
using Autodesk.Autocad.DatabaseServices
(you get those downloading the Object Arx libraries for free from Autodesk):
You will need to access the Editor from an autocad Document.
By the code you've shown, you're probably working with AcadDocument documents.
So, to transform an AcadDocument into a Document, do this:
//These are extension methods and must be in a static class
//Will only work if Doc is saved at least once (has full name) - if document is new, the name will be
public static Document GetAsAppServicesDoc(this IAcadDocument Doc)
{
return Application.DocumentManager.OfType<Document>().First(D => D.Name == Doc.FullOrNewName());
}
public static string FullOrNewName(this IAcadDocument Doc)
{
if (Doc.FullName == "")
return Doc.Name;
else
return Doc.FullName;
}
Once you've got a Document, get the Editor, and the GetSelection(Options, Filter)
The Options contains a property SingleOnly and a SinglePickInSpace. Setting that to true does what you want. (Try both to see wich works better)
//Seleciton options, with single selection
PromptSelectionOptions Options = new PromptSelectionOptions();
Options.SingleOnly = true;
Options.SinglePickInSpace = true;
//This is the filter for blockreferences
SelectionFilter Filter = new SelectionFilter(new TypedValue[] { new TypedValue(0, "INSERT") });
//calls the user selection
PromptSelectionResult Selection = Document.Editor.GetSelection(Options, Filter);
if (Selection.Status == PromptStatus.OK)
{
using (Transaction Trans = Document.Database.TransactionManager.StartTransaction())
{
//This line returns the selected items
AcadBlockReference SelectedRef = (AcadBlockReference)(Trans.GetObject(Selection.Value.OfType<SelectedObject>().First().ObjectId, OpenMode.ForRead).AcadObject);
}
}
this is a direct quote from autocad developer help
http://docs.autodesk.com/ACD/2013/ENU/index.html?url=files/GUID-CBECEDCF-3B4E-4DF3-99A0-47103D10DADD.htm,topicNumber=d30e724932
There is tons of documentation the AutoCAD .NET API.
you will need to have
[assembly: CommandClass(typeof(namespace.class))]
above your namespace if you want to be able to invoke this command from the command line after you NetLoad the .dll, if it is a classLibrary.
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
[CommandMethod("SelectObjectsOnscreen")]
public static void SelectObjectsOnscreen()
{
// Get the current document and database
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
// Start a transaction
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
// Request for objects to be selected in the drawing area
PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();
// If the prompt status is OK, objects were selected
if (acSSPrompt.Status == PromptStatus.OK)
{
SelectionSet acSSet = acSSPrompt.Value;
// Step through the objects in the selection set
foreach (SelectedObject acSSObj in acSSet)
{
// Check to make sure a valid SelectedObject object was returned
if (acSSObj != null)
{
// Open the selected object for write
Entity acEnt = acTrans.GetObject(acSSObj.ObjectId,
OpenMode.ForWrite) as Entity;
if (acEnt != null)
{
// Change the object's color to Green
acEnt.ColorIndex = 3;
}
}
}
// Save the new object to the database
acTrans.Commit();
}
// Dispose of the transaction
}
}
i want to display value of sharepoint people/group value in people editor(web part) when the page is loaded. This is the code that i use to get the value displayed in web part
if(SPContext .Current .ListItem .ID >= 1)
using (SPSite site = new SPSite("sitename"))
{
using (SPWeb web = site.OpenWeb())
{
var id = SPContext.Current.ListItem.ID;
SPList lists = web.Lists["DDClist"];
SPListItem item = lists.GetItemById(id);
{
string test = Convert.ToString(item["Project No"]);
tb_pno.Text = test;
string test2 = Convert.ToString(item["Project Title"]);
tb_pname.Text = test2;
string test3 = Convert.ToString(item["DDC No"]);
tb_idcno.Text = test3;
string test4 = Convert.ToString(item["Date In"]);
TextBox3.Text = test4;
}
}
}
is there a way to do the same thing with people editor?
This is all a little tricky; when I've had to do it before, I use the following to get SPUser object out of a field:
SPUser singleUser = new SPFieldUserValue(
item.Web, item["Single User"] as string).User;
SPUser[] multipleUsers = ((SPFieldUserValueCollection)item["MultipleUsers"])
.Cast<SPFieldUserValue>().Select(f => f.User);
I'm not sure why one user is stored as a string, but multiple users are stored as a specific object; it may also not be consistent in this so you might have to debug a bit and see what the type in your field is.
Once you have these SPUsers, you can populate your PeopleEditor control
using the account names as follows (quite long-winded):
ArrayList entityArrayList = new ArrayList();
foreach(SPUser user in multipleUsers) // or just once for a single user
{
PickerEntity entity = new PickerEntity;
entity.Key = user.LoginName;
entity = peMyPeople.ValidateEntity(entity);
entityArrayList.Add(entity);
}
peMyPeople.UpdateEntities(entityArrayList);
This also performs validation of the users of some kind.
If the page this control appears on may be posted-back, you need the following to be done during the postback in order for the values to be correctly roundtripped; I put it in PreRender but it could happen elsewhere in the lifecycle:
protected override void OnPreRender(EventArgs e)
{
if (IsPostBack)
{
var csa = peMyPeople.CommaSeparatedAccounts;
csa = peMyPeople.CommaSeparatedAccounts;
}
}
If you want to check any error messages that the control generates for you (if the user input is incorrect), you need to have done this switchout already:
var csa = usrBankSponsor.CommaSeparatedAccounts;
csa = usrOtherBankParties.CommaSeparatedAccounts;
//ErrorMessage is incorrect if you haven't done the above
if (!String.IsNullOrEmpty(usrBankSponsor.ErrorMessage))
{
...
}
It's really not very nice and there may be a much better way of handling it, but this is the result of my experience so far so hopefully it will save you some time.
Asked this on the forums as well, but no luck as of yet. What I need to do is set the HTML content of each content block on a given page. It seems that I can set the html value okay, but saving it does not update the actual page.
I'm wondering if it's because there needs to be some sort of save call on the control. There doesn't seem to be any methods available for such an action.
foreach (var c in duplicated.Page.Controls)
{
// go through the properties, se the ID to grab the right text
foreach (var p in c.Properties)
{
if (p.Name == "ID")
{
var content = pageContent.Where(content_pair => content_pair.Key == p.Value).SingleOrDefault();
var control = pageManager.LoadControl(c);
if (control is ContentBlock)
{
var contentBlock = pageManager.LoadControl(c) as ContentBlock;
contentBlock.Html = content.Value;
}
}
}
}
pageManager.SaveChanges(); */
WorkflowManager.MessageWorkflow(duplicated.Id, typeof(PageNode), null, "Publish", false, bag);
The following code may help you achieve what you need.
It will first get the page by its title (I am looking for a page by the title "duplicated" as it's implied by your code).
It generates a new draft of the current page, then go over its controls.
Controls which are detected as content blocks are then iterated in a foreach loop.
As written in the comment inside the foreach loop, you may detect controls by their explicit ID (by the property named "ID") or by their related shared content block (by the property named "SharedContentID") or any other condition (or ignore this condition altogether, which would result in updating all the controls n the page.
Once we have a control to update at hand, you can set its new value depending on the localization settings of your project.
After that the draft is saved and published and optionally a new version is created for it.
PageManager pageManager = PageManager.GetManager();
VersionManager vmanager = VersionManager.GetManager();
PageNode duplicated = pageManager.GetPageNodes().FirstOrDefault(p => p.Title == "duplicate");
if (duplicated != null)
{
var draft = pageManager.EditPage(duplicated.Page.Id, true);
string contentBlockTypeName = typeof(ContentBlock).FullName;
PageDraftControl[] contentBlocks = draft.Controls.Where(contentBlock => contentBlock.ObjectType == contentBlockTypeName).ToArray();
foreach (PageDraftControl contentBlock in contentBlocks)
{
Guid contentBlockId = contentBlock.Id;
//User "SharedContentID" if you are looking up controls which are linked to a shared content block of a specific ID.
//If you you are trying to locate a specific control by its own ID, use the explicit "ID" property instead of "SharedCotentID"
if (contentBlock.Properties.Where(prop => prop.Name == "SharedContentID" && prop.Value.ToString() == contentItemIdstr).FirstOrDefault() != null)
{
ControlProperty htmlProperty = contentBlock.Properties.Where(prop => prop.Control.Id == contentBlockId && prop.Name == "Html").FirstOrDefault();
if (htmlProperty != null)
{
if (AppSettings.CurrentSettings.Multilingual)
{
htmlProperty.GetString("MultilingualValue").SetString(CultureInfo.CurrentUICulture, "New Value");
}
else
{
htmlProperty.Value = "New Value";
}
}
}
}
draft = pageManager.SavePageDraft(draft);
draft.ParentPage.LockedBy = Guid.Empty;
pageManager.PublishPageDraft(draft);
pageManager.DeletePageTempDrafts(draft.ParentPage);
//Use the 2 next lines to create a new version of your page, if you wish.
//Otherwise the content will be updated on the current page version.
vmanager.CreateVersion(draft, draft.ParentPage.Id, true);
vmanager.SaveChanges();
pageManager.SaveChanges();
}
I hope this code helps.
Alon.