how to use c# code in the page source of custom newform of a list to update some fields of it - sharepoint-2010

I was looking for a solution where I'll populate the value from one list and display it to the another list. I have now got some code but not sure how use it.
I have to now use some c# code into page source of custom newform of a list. This code will actually retrieve the user information and update to the field in the custom newform in the list.
Following C# code I want to use in newform page source using sharepoint designer
SPSite _site = SPContext.Current.Site;
ServerContext serverContext = ServerContext.GetContext(_site);
UserProfileManager myUserProfile = new UserProfileManager(serverContext);
UserProfile currentUserProfile = myUserProfile .GetUserProfile(System.Web.HttpContext.Current.User.Identity.Name);
string departmentName = (string)currentUserProfile["department"].Value;
string managerName = (string)currentUserProfile["manager"].Value;
_site.RootWeb.Dispose();
_site.Dispose();
Please help me to get this work.

SharePoint Designer removes various types of code, including all C#, in order to prevent vulnerabilities from accidentally being introduced. To use your C# code you will need to create and deploy a solution package with VIsual Studio. Instead, your best bet is probably to use JavaScript. Here is documentation for 2013, here is a utility to simplify retrieving the data in 2010, and here is some code that will get you very close to what you're trying to do.
Copy of the code in case that link dies:
<script type="text/javascript">
// ensure system stuff is loaded before we start calling client object model
ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js");
// create context variables
var context = null;
var web = null;
var currentUser = null;
// this function calls object model to determine current user name
function getWebUserData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),
Function.createDelegate(this, this.onFailureMethod));
}
// this function gets called if we get current user name successfully
function onSuccessMethod(sender, args) {
var loginName = web.get_currentUser().get_loginName();
// this call requests the value for property named "Title" for current user name
GetUserProperty(loginName, "Title");
}
// yes, things failed; I ignore it here but you can display an alert
function onFailureMethod(sender, args) {
// Unable to find user profile
}
// function which retrieves the value of the property
function GetUserProperty(accountName, propertyName) {
// constructing the call to a user profile using web services
var soapMessage = '<?xml version="1.0" encoding="utf-8"?>'
+ '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
+ '<soap:Body>'
+ ' <GetUserPropertyByAccountName
xmlns="http://microsoft.com/webservices/SharePointPortalServer/UserProfileService">'
+ ' <accountName>' + accountName + '</accountName>'
+ ' <propertyName>' + propertyName + '</propertyName>'
+ ' </GetUserPropertyByAccountName>'
+ ' </soap:Body>'
+ '</soap:Envelope>'
// making a call with jQuery
$.ajax({
url: '/_vti_bin/UserProfileService.asmx',
type: "POST",
dataType: "xml",
data: soapMessage,
complete: displayProfileProperty,
contentType: "text/xml; charset=\"utf-8\""
});
return false;
}
// things went well and we get results back
function displayProfileProperty(xmlHttpRequest, status)
{
// the result is burried in XML markup so we look for the right node
$(xmlHttpRequest.responseXML).find('Values').each(function()
{
// get the text property of the node and display it
var name = $(this).find('Value').text();
alert(name);
});
}

Related

Shopware 6 custom element type image not showing any data on storefront

I have created my component to add some desired config fields in Shopware 6. Everything is working fine but one problem that is image is looking as it is being saved in the administration but is not showing any src or else in dump.
And here is my dump preiew having #data null.
can anyone tell what should I do else here?
I will be very thankful.
There is a guide in the docs that explains exactly what your case is.
You can likely extend the \Shopware\Core\Content\Media\Cms\ImageCmsElementResolver and override the getType function:
public function getType(): string
{
return 'my-component-name';
}
The important part of the default ImageCmsElementResolver is the loading the media information. For that you also need in your CMS element resolver. I explain some parts of the existing ImageCmsElementResolver so you can see which steps you need:
public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
{
// read the configuration, that is defined in the Admin JS. Likely also media for you
$mediaConfig = $slot->getFieldConfig()->get('media');
// if this config is NOT containing useful info
if (
$mediaConfig === null
|| $mediaConfig->isMapped()
|| $mediaConfig->isDefault()
|| $mediaConfig->getValue() === null
) {
// return nothing
return null;
}
// otherwise use the configured value as mediaId to load the media entry from the database
$criteria = new Criteria([$mediaConfig->getStringValue()]);
$criteriaCollection = new CriteriaCollection();
$criteriaCollection->add('media_' . $slot->getUniqueIdentifier(), MediaDefinition::class, $criteria);
// return the criterias to execute later, when all needed entities for the CMS page are fetched
return $criteriaCollection;
}
Now the data is fetched and as next step you need to put it into a variable accessible from the Twig template. For this you write into the same CMS element resolver this:
public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
{
$config = $slot->getFieldConfig();
$image = new ImageStruct();
// this is important for accessing data in Twig
$slot->setData($image);
// read the config again
$mediaConfig = $config->get('media');
// if the configuration looks promising
if ($mediaConfig && $config->isStatic() && $mediaConfig->getValue()) {
$image->setMediaId($config->getStringValue());
// look up the media from the entity loading step
$searchResult = $result->get('media_' . $slot->getUniqueIdentifier());
if (!$searchResult) {
return;
}
/** #var MediaEntity|null $media */
$media = $searchResult->get($config->getValue());
// if we do not have a media, then skip it
if (!$media) {
return;
}
// set the media entity to the slot data we just assigned to the slot
$image->setMedia($media);
}
}
After that you should have more info in the slot variable in Twig to embed a media.

non-invocable member 'File' cannot be used like a method error message- what am I missing?

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

RazorEngine Error trying to send email

I have an MVC 4 application that sends out multiple emails. For example, I have an email template for submitting an order, a template for cancelling an order, etc...
I have an Email Service with multiple methods. My controller calls the Send method which looks like this:
public virtual void Send(List<string> recipients, string subject, string template, object data)
{
...
string html = GetContent(template, data);
...
}
The Send method calls GetContent, which is the method causing the problem:
private string GetContent(string template, object data)
{
string path = Path.Combine(BaseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return Engine.Razor.RunCompile(content, "htmlTemplate", null, data);
}
I am receiving the error:
The same key was already used for another template!
In my GetContent method should I add a new parameter for the TemplateKey and use that variable instead of always using htmlTemplate? Then the new order email template could have newOrderKey and CancelOrderKey for the email template being used to cancel an order?
Explanation
This happens because you use the same template key ("htmlTemplate") for multiple different templates.
Note that the way you currently have implemented GetContent you will run into multiple problems:
Even if you use a unique key, for example the template variable, you will trigger the exception when the templates are edited on disk.
Performance: You are reading the template file every time even when the template is already cached.
Solution:
Implement the ITemplateManager interface to manage your templates:
public class MyTemplateManager : ITemplateManager
{
private readonly string baseTemplatePath;
public MyTemplateManager(string basePath) {
baseTemplatePath = basePath;
}
public ITemplateSource Resolve(ITemplateKey key)
{
string template = key.Name;
string path = Path.Combine(baseTemplatePath, string.Format("{0}{1}", template, ".html.cshtml"));
string content = File.ReadAllText(path);
return new LoadedTemplateSource(content, path);
}
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context)
{
return new NameOnlyTemplateKey(name, resolveType, context);
}
public void AddDynamic(ITemplateKey key, ITemplateSource source)
{
throw new NotImplementedException("dynamic templates are not supported!");
}
}
Setup on startup:
var config = new TemplateServiceConfiguration();
config.Debug = true;
config.TemplateManager = new MyTemplateManager(BaseTemplatePath);
Engine.Razor = RazorEngineService.Create(config);
And use it:
// You don't really need this method anymore.
private string GetContent(string template, object data)
{
return Engine.Razor.RunCompile(template, null, data);
}
RazorEngine will now fix all the problems mentioned above internally. Notice how it is perfectly fine to use the name of the template as key, if in your scenario the name is all you need to identify a template (otherwise you cannot use NameOnlyTemplateKey and need to provide your own implementation).
Hope this helps.
(Disclaimer: Contributor of RazorEngine)

Marketo rest Api create lead

I have a question about this create/Update leads API, http://developers.marketo.com/documentation/rest/createupdate-leads/.
There is no sample code for C# or JAVA. Only ruby available. So I have to try it by myself. But I always get null return from the response.
Here is my code:
private async Task<CreateLeadResponseResult> CreateLead(string token)
{
string url = String.Format(marketoInstanceAddress+"/rest/v1/leads.json?access_token={0}", token);
var fullUri = new Uri(url, UriKind.Absolute);
CreateLeadResponseResult createLeadResponse = new CreateLeadResponseResult();
CreateLeadInput input = new CreateLeadInput { email = "123#123.com", lastName = "Lee", firstName = "testtesttest", postCode = "00000" };
CreateLeadInput input2 = new CreateLeadInput { email = "321#gagaga.com", lastName = "Lio", firstName = "ttttttt", postCode = "00000" };
List<CreateLeadInput> inputList = new List<CreateLeadInput>();
inputList.Add(input);
inputList.Add(input2);
CreateLeadRequest createLeadRequest = new CreateLeadRequest() { input = inputList };
JavaScriptSerializer createJsonString = new JavaScriptSerializer();
string inputJsonString = createJsonString.Serialize(createLeadRequest);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(fullUri.OriginalString, inputJsonString).ConfigureAwait(false);
// I can see the JSON string is in the message body in debugging mode.
if (response.IsSuccessStatusCode)
{
createLeadResponse = await response.Content.ReadAsAsync<CreateLeadResponseResult>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return createLeadResponse;}
//get null here.
Thank you.
-C.
The best way to debug this is to capture the exact URL, parameters and JSON that are submitted by your app and try submitting those manually via a tool like Postman (Chrome plug-in) or SOAP UI. Then you see the exact error message, which you can look up here: http://developers.marketo.com/documentation/rest/error-codes/. Based on that you can update your code. I don't know much about Java, but this is how I got my Python code to work.
Your example code was really helpful in getting my own implementation off the ground. Thanks!
After playing with it for a bit, I realized that the JavaScriptSerializer step is unnecessary since PostAsJsonAsync automatically serializes whatever object you pass to it. The double serialization prevents Marketo's API from processing the input.
Also, I agree with Jep that Postman is super helpful. But in the case of this error, Postman was working fine (using the contents of inputJsonString) but my C# code still didn't work properly. So I temporarily modified the code to return a dynamic object instead of a CreateLeadResponseResult. In debugging mode this allowed me to see fields that were discarded because they didn't fit the CreateLeadResponseResult type, which led me to the solution above.

my zend session name spacing does not work

I am new to Zend and very keen to learn, so I would really appreciate some help and guidance.
I am trying to create a 'method in a class' that will save the session variables of product pages visited by members to a site i.e
i,e examplesite com/product/?producttype= 6
I want to save the number 6 in a session variable. I also do not want to have a global session for the entire site; I just want it for selected pages. So, I guess I have to have Zend_Session::start() on the selected page; but I am not clear how this should be done.
Should I instantiate it in the page view page. i.e products page or do this in the indexAction() method for the products page. I have attempted to instantiate it below but it did not work.
public function rememberLastProductSearched()
{ //my attempt to start a session start for this particular page.
Zend_Session::start();
}
$session->productSearchCategory = $this->_request->getParam('product-search-category');
return" $session->productSearchCategory ";
}
else
{
//echo " nothing there
return " $session->productSearchCategory";
//";
}
}
With the rememberLastProductSearched() method I was trying to get the method to first check whether the user had searched for a new product or just arrived at the page by default. i.e whether he had used the get() action to search for a new product. If the answer is no, then I wanted the system to check whether their had been a previous saved session variable. so in procedural syntax it would have gone like this:
if(isset($_Get['producttype']))
{
//$dbc database connection
$producttype = mysqli_real_escape_string($dbc,trim($_GET['producttype']));
}
else
if(isset($_SESSION['producttype'])){
$producttype = mysqli_real_escape_string($dbc,trim($_SESSION['producttype']));
}
Can you please help me with the Zend/oop syntax. I am totally confused how it should be?
you're asking about simple work flow in an action, it should begin something like:
//in any controller
public function anyAction()
{
//open seesion, start will be called if needed
$session = new Zend_Session_Namespace('products');
//get value
$productCategory = $this->getRequest()->getParam('producttype');
//save value to namespace
$session->productType = $productCategory;
//...
}
now to move this off to a separate method you have to pass the data to the method...
protected function rememberLastProductSearched($productType)
{
//open seesion, start will be called if needed
$session = new Zend_Session_Namespace('products');
$session->productType = $productType;
}
So now if you want to test for presence of a value...
//in any controller
public function anyAction()
{
//open seesion, call the namespace whenever you need to access it
$session = new Zend_Session_Namespace('products');
if (!isset($session->productType)) {
$productCategory = $this->getRequest()->getParam('producttype');
//save value to session
$this->rememberLastProductSearched($productCategory)
} else {
$productCategory = $session->productType;
}
}
That's the idea.
Be mindful of your work flow as it can sometimes be very simple to inadvertently overwrite your session values.
$session = new Zend_Session_Namespace("productSearch");
if ($this->getRequest()->getParam('producttype')) { //isset GET param ?
$session->productType = $this->getRequest()->getParam('producttype');
$searchedProductType = $session->productType;
} else { //take the session saved value
if ($session->productType) {
$searchedProductType = $session->productType;
}
}
//now use $searchedProductType for your query