Save and New Button will not clear fields - button

I have 3 custom visual force pages. a view which views the record, edit which edits and a new that makes a new record. Edit and New have a save and new button. When I click save and new I need a redirect, a new record to be made, and few of the fields to be cleared however all the previous data is being transferred over on the redirect.
My apex code..
public PageReference saveAndNew() {
try {
// Save the current sObject
sController.save();
Schema.DescribeSObjectResult describeResult = sController.getRecord().getSObjectType().getDescribe();
// Create PageReference for creating a new sObject and add any inbound query string parameters.
PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e?' + queryString);
// Don't redirect with the viewstate of the current record.
pr.setRedirect(true);
eventPackageRevenueBreakdown = new eventPackageRevenueBreakdown__c();
eventPackageRevenueBreakdown.Name = null;
eventpackageRevenueBreakdown.AdminIsIncludedInInclusivePrice__c = false;
return pr;
} catch(Exception e) {
// Don't redirect if something goes wrong. May be a validation or trigger issue on save.
ApexPages.addMessages(e);
return null;
}
}

I suggest you check Using the transient Keyword. Mark data, which you don't want to be transferred, as transient.

Related

Trying to set RadTreeView node checked status programatically from persistence

There must be something I'm missing here. I have two instances of RadTreeView, for which I store node check data in a cookie. Upon page load, I then want to read this cookie, and set checked status accordingly.
So I have this OnDataBound event:
protected void RadTreeView1_OnDataBound(object sender, EventArgs e)
{
HttpCookie checkedCookie = Request.Cookies[DataType + "Checked"];
if (checkedCookie != null)
{
var cookieValue = checkedCookie.Values["Checked"];
if (cookieValue != null)
{
var checkedNodeValues = cookieValue.Split('*');
foreach (string nodeValue in checkedNodeValues)
{
RadTreeNode checkedNode = RadTreeView1.FindNodeByValue(HttpUtility.UrlDecode(nodeValue));
if (checkedNode != null)
checkedNode.Checked = true;
}
}
}
}
And in the foreach loop, I find a corresponding node for every cookie value. What's more is, their initial Checked status is false.
So why are all other nodes also getting checked?
Try using the RadPersistenceFramework. Adding a single entry for your treeview to the PersistenceManager (or PersistenceManagerProxy) control should let you store the checked state. You can see this here http://demos.telerik.com/aspnet-ajax/treeview/examples/applicationscenarios/persisting-treeview-settings/defaultcs.aspx?product=persistenceframework
Of course, storing the data depends a bit on your case (you can have a custom provider and still keep the data in a cookie, or you can keep things in a database, whatever works for you: http://demos.telerik.com/aspnet-ajax/persistence-framework/examples/custom-storage-provider/defaultcs.aspx).

How to Update an Appointment from Exchange Web Service Managed API 2.0 in ASP.NET

iam using the EWS Managed API 2.0 to create an Appontment. It works fine. But want to Update an existing Appointment, too.
I read that i need the appointment ID to specify which appoint should be edited. But where is the ID?
Here is how i create an Appointment:
'Creates the Appointment
Dim appointment As New EWS.Appointment(esb)
appointment.Subject = txtThema.Text
appointment.Body = txtBemerkung.Text
appointment.Start = Von
appointment.End = Bis
appointment.Location = lbRaumInfo.Text
'Adds the Attendees
For i = 1 To emaillist.Length - 1
appointment.RequiredAttendees.Add(emaillist(i))
Next
'Sending
appointment.Save(EWS.SendInvitationsMode.SendToAllAndSaveCopy)
The temporary unique ID for the AppointmentItem can be retrieved via the ItemSchema's Id property. It should be present after saving the AppointmentItem.
ItemId id = appointment.Id;
The ItemId can change if the AppointmentItem is moved or copied.
A way to do it, is to use the Unique ID as suggested by SilverNinja, and as he said that this is not permanent ID and it can be changed once the appointment is moved to different folder (like if it has been deleted for example).
A way to deal with this problem is to create an extended property, and put guid for the appointment, and it wont change unless you made a copy from another appointment (after all it is just a property)
I have it in C# , but I am sure it is pretty easy to convert to VB
private static readonly PropertyDefinitionBase AppointementIdPropertyDefinition = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "AppointmentID", MapiPropertyType.String);
public static PropertySet PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, AppointementIdPropertyDefinition);
//Setting the property for the appointment
public static void SetGuidForAppointement(Appointment appointment)
{
try
{
appointment.SetExtendedProperty((ExtendedPropertyDefinition)AppointementIdPropertyDefinition, Guid.NewGuid().ToString());
appointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToNone);
}
catch (Exception ex)
{
// logging the exception
}
}
//Getting the property for the appointment
public static string GetGuidForAppointement(Appointment appointment)
{
var result = "";
try
{
appointment.Load(PropertySet);
foreach (var extendedProperty in appointment.ExtendedProperties)
{
if (extendedProperty.PropertyDefinition.Name == "AppointmentID")
{
result = extendedProperty.Value.ToString();
}
}
}
catch (Exception ex)
{
// logging the exception
}
return result;
}

open a new window of view when call controller from Jquery Ajax post call

I'm using ASP.Net MVC2. I'm trying to open a new window of view when call controller from Jquery Ajax post call.
here is my code..
in ascx page..
$('#DeleteButton').click(function () {
var isLineChecked = $(':checkbox:checked', '#providerSearchResultsTable').length;
if (isLineChecked == 0) {
alert("Please select at least one row ");
return false;
}
else {
var params = {
Id: gaiSelected.join(',')
};
alert(params);
$.ajax({
type: "Post",
url: "SelectProviderAndContact",
data: params,
success: function (html) {
**//$('#SelectProviderAndContact').html(html);**
}
});
}
});
here is my controller Action method
[SessionFilter]
public ActionResult SelectProviderAndContact(string Id)
{
try
{
List<ProviderBaseInfo> providerList = null;
string[] internalProviderIDs = Id.Split(",".ToCharArray());
//string[] billingProviderNames = billingProvider.Split(",".ToCharArray());
IStateBag stateBag = _commonModel.GetStateBag();
//stateBag.SetValue("InternalProviderId", Id);
List<Guid> internalProviderIds = new List<Guid>();
foreach (var a in internalProviderIDs)
{
internalProviderIds.Add(new Guid(a));
}
List<Contacts> providerContactList = _providerModel.GetProviderContactlist(internalProviderIds);
if (providerContactList.Count <= 0)
{
//IStateBag stateBag = GetStateBag();
List<ProviderBaseInfo> providers = (List<ProviderBaseInfo>)stateBag.GetValue(ProviderListCache);
if (providers == null)
{
providerList = _providerModel.GetProviderCompleteList(null, null, null, null, Id).ToList();
}
else
{
providerList = providers.Where(x => internalProviderIds.Contains(x.InternalProviderId)).ToList();
}
providerContactList = _providerModel.GetContactlistbyInsertingProviders(providerList);
}
ViewData["ProviderNotFound"] = false;
// ViewData["ProviderName"] = new SelectList(billingProvider.Select(x => new { value = x, text = x }), "value", "text");
var Provider = new[] {
new { ProviderId = "A", Providername = "A" }
//new DataContracts.RegionKeyValues { RegionId = "B", RegionValue = "B" },
//new DataContracts.RegionKeyValues { RegionId = "D", RegionValue = "D" }
};
ViewData["ProviderName"] = new SelectList(Provider, "ProviderId", "Providername");
**return View("SelectProviderAndContact",providerContactList);**
}
catch (FaultException<MedicareFault> ex)
{
if (ex.Code.Name == typeof(ArgumentException).Name)
{
ViewData["ProviderNotFound"] = true;
ViewData["Error"] = ex.Reason;
return View((object)null);
}
else
{
ViewData["Error"] = Errors.Common.UnknownError;
return View((object)null);
}
}
catch
{
ViewData["Error"] = Errors.Common.UnknownError;
return View((object)null);
}
}
and I have created SelectProviderAndContact.aspx in view.
Please any one help me to open another window with SelectProviderAndContact.aspx
from ajax post call.
Your jquery will have to do almost all the work in opening a window. Using the window.open() method in your javascript you can make your controller send back a specific argument that causes it to open a new window with a certain URL (i.e. TheSmallPopupPageThatViewsResults.aspx?resultId=12345 or something).
Your controller would just decide whether or not to tell the view to open the new window and the view would then open it if it is told to.
With your specific implementation, you may have to create a model or something that stores results in the database so that the controller can save the result and the action and view that are for the popup page can then access that result. Another way of doing it would be to have the arguments that the popup page is called with determine what is viewed on the page. This would eliminate the need for another model, but your urls could get really long really fast if you have a lot of data and I believe that there is generally a limit to how long those urls can be.
I would recommend using JSON or XML to return the data to the javascript so that you can extend the returned object as much as needed. The way I have done it in the past is made several XML tags like <alert>, <refresh>, <redirect>, <somePageSpecificAction>, etc that I have jquery parse using $(theEnclosingTag).each( function () { //...parse here }).
I use mainly MVC3 so I don't know if this is supported in MVC2, but changing ActionResult to JsonResult for the return type and using return this.Json(new { put = "data here" }); for your return statements makes it really easy to use json.
Also, It may be beneficial to use a different action method to process ajax requests. You would then have one action that displays the page, another action to process ajax requests from that page (it could be decorated with [HttpPost] or something), and another method for your popup page view. That would also keep your code short and easier to read. Having long controller methods can get really confusing later down the line when you try to find the location of a specific bug.
EDIT: A specific example: Assuming MVC3 (since that is what I use...I think you can find other ways of doing this...you could use an xml serializer and just output xml) you have your page (Action #1) that displays with all your buttons and stuff (this is where you javascript containing the $("#DeleteButton") and such goes as well). Your javascript makes its AJAX call to another action (SelectContactAJAX or something...this is action #2) with a few arguments which has a return type of JsonResult. Your javascript gets the response back from that ajax-specific action and the response tells it "open a window with the URL /SelectContactForm?choiceId=12345" (or something). The choiceId is a reference that would be used in the background for the SelectContactForm action (yet another separate action...action #3) to know what to display. Your ajax would then call window.open("/SelectContactForm?choiceId=12345") and when the window opens, it calls action #3 which looks up the reference for what it should be displaying and then shows that to the user.
As for getting feedback on what the user entered in the new window and having the original page react, there are various ways in javascript to listen for window closings and such, but I haven't ever had to use this in one of my applications and it is a bit out of the scope of this question.
use colorbox jquery plugin
http://www.jacklmoore.com/colorbox
write code in .aspx page to call .ascx page
parent.$.fn.colorbox({ href: '/IGTR/SaveIGTRPreference/' + id + '?t=' + Math.random(), height: "400", width: "800", overlayClose: false, escKey: false
});
Here SaveIGTRPreference is .ascx page

Event to create a Page when a user creates one Page in SDL Tridion 2011 SP1

I am working on triggering an event to create a page automatically, when user creates a page.
namespace TestEventHandler
{
[TcmExtension("MyEventHandlerExtension")]
public class MyEventHandler : TcmExtension
{
public MyEventHandler()
{
Subscribe();
}
public void Subscribe()
{
EventSystem.Subscribe<Page, SaveEventArgs>(HandlerForProcessed, EventPhases.Processed);
//EventSystem.Subscribe<Page, PublishEventArgs>(HandlerForInitiated, EventPhases.Initiated);
}
private void HandlerForProcessed(Page subject, SaveEventArgs args, EventPhases phase)
{
//create page.
Tridion.ContentManager.Session mySession = new Tridion.ContentManager.Session(#"user");
XmlElement XmlElement = null;
Page newPage = new Page(XmlElement, mySession);
newPage.Title = subject.Title + "_auto";
newPage.FileName = subject.FileName + "_auto";
newPage.PageTemplate = subject.PageTemplate;
newPage.Save(true);
newPage.CheckOut();
}
}
}
It's not creating the page automatically. I think some modification is required for this code.
I am getting error "Impersonation by this user requires the Machinename\MTSUser account to be configured as impersonation user".
Can anyone help with the modifications needed? I am using the TOM.net API for this.
Thank you.
The error is due to the new Session you are trying to create. That should not be necessary. You can get it from Page subject.Session.
Additionally, you are using the wrong constructor for the Page. Check out the documentation.
Sample code:
Page page = page = new Page(session, new TcmUri(sg));
page.Title = theTitle;
page.FileName = new Regex("\\W").Replace(theTitle, "");
page.PageTemplate = session.GetObject(pt) as PageTemplate;
ComponentTemplate componentTemplate = session.GetObject(ct) as ComponentTemplate;
page.ComponentPresentations.Add(
new ComponentPresentation(component, componentTemplate));
page.Save(true);
The parameters you need are sg, theTitle, pt, ct, component. You could read them from Folder metadata for example.

ASP.NET MetaTags from database

I'm developing a web site in which the site manager can change dinamically the MetaTags for the web site in a cms, storing those MetaTags in a MySql database.
In the public master.page, in the Page_Load event, I get those MetaTags from the database
sTitle = get_from_data_base();
using (HtmlMeta mTag = new HtmlMeta())
{
mTag .Name = "Title";
mTag .Content = sTitle;
Page.Header.Controls.Add(mTag);
}
The problem is everytime a page loads, the load event of the master.page is loading from database those MetaTags.
How can I keep in cache or something similar the metatags once they have been loaded so the site doesn't access the database on every request?
How can the site knows when those MetaTags have changed to load them again?
Please, could you provide an example.
Thanks so much.
One of the solutions to do is to load the data once in the global.asax application start event and add the result in application object then in each page you need it, load it from the application object.
When the data is changed in the database, access the application object and update it as well.
If you don't know how to deal with global.asax or application object, i will post code.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
string sTitle = get_from_data_base();
Application.Add("sTitle", sTitle);
}
public string get_from_data_base()
{
//update this to call the database and get the data
return "Your data";
}
In your pages write the following:
string sTitle = Application["sTitle"].ToString();
using (HtmlMeta mTag = new HtmlMeta())
{
mTag.Name = "Title";
mTag.Content = sTitle;
Page.Header.Controls.Add(mTag);
}
While your manage is updating the metatag append the following line
Application["sTitle"] = "You manager entered string";
Finally, after your answers and reading on the Internet I went for the Cache object instead Application object. I have read is better, so my final aproach for this would be to add this on the global class and access this method from my master.pages
public static MetaTagsDN get_meta_tags()
{
MetaTagsDN oTags;
if (HttpRuntime.Cache["MetaTags"] == null)
{
MetaTagsLN ln = new MetaTagsLN();
oTags = ln.get_metatags();
HttpRuntime.Cache["MetaTags"] = oTags;
}
else
{
oTags = (MetaTagsDN)HttpRuntime.Cache["MetaTags"];
}
return oTags;
}
What do you think?
Thanks for helping me...

Resources