save form values through script file in umbraco - asp.net-mvc

hello i want to save the value of umbraco form in database for this i have made script file and in this script file i have created function to save data and called this function in same script file and this script file is used in macro and i have called this macro in template of my page but it is not working will this approach is proper or i have to something else my basic aim is to save data in database without creating my usercontrol
code is
#functions
{
public void AddToCart()
{
string con = System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString();
SqlConnection OnCon = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString());
ItemsDataContext db = new ItemsDataContext(con);
var request = HttpContext.Current.Request;
string itemcode= request.Form["ItemCode"].ToString();
string itemname = request.Form["ItemName"].ToString();
string itemcategory = Request.Form["ItemCategory"].ToString();
string userid = "Pallavi";
db.sp_AddItems(userid, itemcode, itemcategory, itemname, 0);
HttpContext.Current.Session["UserId"] = "Pallavi";
}
}
#if (!IsPost)
{
AddToCart();
}
and called this macro on template
<umbraco:Macro Alias="Uc_Cart" runat="server"></umbraco:Macro>

You approach is wrong. You must use the methods that Umbraco provides in their API and do not try to write data into the database directly.
Try this code to create an new document from Razor code:
#using umbraco.BusinessLogic;
#using umbraco.cms.businesslogic.web;
#{
DocumentType dt = DocumentType.GetByAlias("Textpage");
User author = umbraco.BusinessLogic.User.GetUser(0);
Document doc = Document.MakeNew("My new document", dt, author, parentID);
}
The example above is for Umbraco 4.x. If you're using Umbraco v6.x you could also use the new API methods:
#{
// get an instance of the contentService
var contentService = ApplicationContext.Services.ContentService;
// create new content, the last param is the userId and is optional [default = 0]
IContent newContent = contentService.CreateContent("My new document", parentID, "Textpage", 0);
// set property values
newContent.SetValue("propertyAlias", "Value");
// save (or save and publish)
contentService.Save(newContent);
}

Related

ASP.NET MVC DevExpress XtraReport with getting parameter from View

I want to generate a report that contains data from a database using a filter stored in a ViewData.
My question is how I will pass the ViewData value of the report as a parameter to display some data.
Controller :
var Soc = (string)TempData["Societe"];
XtraReport report = new Training.UI.Web.Reporting.Etat1();
report.DataSource = from p in db.TEntreprises
where p.EntNom == Soc
select p;
report.Parameters.Add(new DevExpress.XtraReports.Parameters.Parameter() { Name = "EntNom", Type = typeof(String), Value = Soc, Description = "NomEntreprise" });
ViewData["Report"] = report;
return PartialView("DocumentViewerPartial");
View :
#Html.DevExpress().DocumentViewer(settings =>
{
settings.Name = "documentViewer1";
settings.StylesSplitter.SidePaneWidth = 340;
settings.Report = (Training.UI.Web.Reporting.Etat1) ViewData["Report"];
settings.CallbackRouteValues = new { Controller = "Etat1", Action = "DocumentViewerPartial" };
settings.ExportRouteValues = new { Controller = "Etat1", Action = "ExportDocumentViewer" };
}).GetHtml()
And I have no data in the XtraReport
To apply the values to the report, create a string that contains the report name and the submitted values, and pass this string to the viewer’s OpenReport method.
The example below demonstrates how to do the following:
Create a page with a document viewer and button.
Create a string with the report name and a predefined parameter value and pass this string to the viewer’s OpenReport method on a button click.
Viewer.cshtml
<script type="text/javascript">
function OnClick() {
var reportName = "XtraReport1";
var paramName = "strParam";
var paramValue = "42";
var reportUrl = reportName + '?' + paramName + '=' + paramValue;
WebDocumentViewer1.OpenReport(reportUrl);
}
</script>
#Html.DevExpress().Button(settings => {
settings.Name = "dxOpenButton";
settings.Text = "Submit parameter";
settings.ClientSideEvents.Click = "OnClick";
}).GetHtml()
#Html.DevExpress().WebDocumentViewer(settings => {
settings.Name = "WebDocumentViewer1";
}).Bind("XtraReport1").GetHtml()
When you call the viewer’s OpenReport method, the reporting engine executes a report name resolution service. This service creates a report instance and returns it to the viewer. Implement this service to apply the parameter values to the report. The string argument from the OpenReport method is passed to the service’s method that returns a report instance. In this method, do the following:
Parse the string argument to extract the report name and parameter values.
Create a report instance and apply the parameter values to it. Reference each parameter by name in the report’s Parameters collection and assign the value to the parameter’s Value property.
If you want custom UI elements to be the only way to submit parameter values, hide the Parameters Panel. To do this, disable the Visible property for all report parameters. If you want users to submit parameter values from both the panel and custom UI elements, disable the report’s RequestParameters property.
Return the report instance.
When you create a Web Reporting application from the DevExpress Template Gallery, you can add the Report Storage service to the application. This service will be utilized as a report name resolution service in your application. For this, implement the service’s GetData method as follows:
CustomReportStorageWebExtenstion.CS
public override byte[] GetData(string url) {
try {
// Parse the string with the report name and parameter values.
string[] parts = url.Split('?');
string reportName = parts[0];
string parametersQueryString = parts.Length > 1 ? parts[1] : String.Empty;
// Create a report instance.
XtraReport report = null;
if (Directory.EnumerateFiles(reportDirectory).
Select(Path.GetFileNameWithoutExtension).Contains(reportName)) {
byte[] reportBytes = File.ReadAllBytes(Path.Combine(reportDirectory, reportName + FileExtension));
using (MemoryStream ms = new MemoryStream(reportBytes))
report = XtraReport.FromStream(ms);
}
if (report != null) {
// Apply the parameter values to the report.
var parameters = HttpUtility.ParseQueryString(parametersQueryString);
foreach (string parameterName in parameters.AllKeys) {
report.Parameters[parameterName].Value = Convert.ChangeType(
parameters.Get(parameterName), report.Parameters[parameterName].Type);
}
// Disable the Visible property for all report parameters
// to hide the Parameters Panel in the viewer.
foreach (var parameter in report.Parameters) {
parameter.Visible = false;
}
// If you do not hide the panel, disable the report's RequestParameters property.
// report.RequestParameters = false;
using (MemoryStream ms = new MemoryStream()) {
report.SaveLayoutToXml(ms);
return ms.ToArray();
}
}
} catch (Exception) {
// ...
}
To apply parameter values from a URL query string to a report, implement the viewer’s action method as follows:
Create a report instance and apply the parameter values to it. Reference each parameter by name in the report’s Parameters collection and assign the value to the parameter’s Value property.
If you want a URL’s query string to be the only way to submit parameter values, hide the Parameters Panel. To do this, disable the Visible property for all report parameters. If you want users to submit parameter values from both the panel and a URL’s query string, disable the report’s RequestParameters property.
Return a report view.
The example below demonstrates how to implement the viewer’s action method to apply the parameter value from the query string of the following URL: https://localhost:5001/Home/Viewer?intParam=42.
HomeController.cs
public ActionResult Viewer(int? intParam) {
var report = new XtraReport1();
report.Parameters["intParam"].Value = intParam;
report.Parameters["intParam"].Visible = false;
return View(report);
}
enter image description here

Web API 2.2 - OData v4 (Manually Parsing Uri + Expanding)

I have an ODataController with a Get method as such:
public IHttpActionResult Get(ODataQueryOptions<MyModel> queryOptions) {
IQueryable<MyModel> models = _Models.AsQueryable(); // _Models Defined in Controller as List<MyModel> and is already populated with nested data for both .LevelOne and .LevelOne.LevelTwo which are two other Lists.
Uri fullrequest = Request.GetRequestContext().Url.Request.RequestUri; // http://localhost:8080/odata/Root?$expand=LevelOne($expand=LevelTwo)
Uri serviceroot = new Uri(controller.GetLeftPart(UriPartial.Path).Replace("/Root", "")); // http://localhost:8080/odata
String metadata = service + "/$metadata"; // http://localhost:8080/odata/$metadata
IEdmModel model = EdmxReader.Parse(XmlTextReader.Create(metadata));
ODataUriParser parser = new ODataUriParser(model, serviceroot, fullrequest);
SelectExpandClause selectAndExpand = parser.ParseSelectAndExpand();
//Only one of the two below lines is ever commented in...
Request.ODataProperties().SelectExpandClause = queryOptions.SelectExpand.SelectExpandClause; // This line will work
Request.ODataProperties().SelectExpandClause = selectAndExpand; // This line will not work
return Ok(models);
}
using my manually parsed selectAndExpand does not expand the dataset, but using the predefined queryOptions one does. Any ideas why? Both objects appear to contain the same information while viewed in the debugger, but I must be missing something. I want to be able to parse the URI myself, without the need for the ODataQueryOptions at all.
What I ended up doing, was building a new ODataQueryOptions object based off the original request, and then pulling just the SelectExpandClause from that. It doesn't answer my initial question, but it is a somewhat working solution for not having to pass in a ODataQueryOptions parameter. See my Code below:
public IHttpActionResult Get() {
//Get Queryable Item (in this case just a list made queryable)
IQueryable<MyModel> models = _Models.AsQueryable();
//Create new ODataQueryContext based off initial request (required to create ODataQueryOptions)
ODataQueryContext selectAndExpandContext = new ODataQueryContext(Request.ODataProperties().Model, typeof(MyModel), Request.ODataProperties().Path);
//Create new ODataQueryOptions based off new context and original request
ODataQueryOptions<Employee> selectAndExpandOptions = new ODataQueryOptions<Employee>(selectAndExpandContext, Request);
//Attach Select + Expand options to be processed
if (selectAndExpandOptions.SelectExpand != null) {
Request.ODataProperties().SelectExpandClause = selectAndExpandOptions.SelectExpand.SelectExpandClause;
}
return Ok(models);
}

Linq query returns sql and not data from database

I'm not sure what the problem is but I cant seem to get my program to display the correct information. The requirements for my application are to take a pdf and populate the form fields with information from a database. The problem is that it does not return the information from the database and instead returns the sql generated from entity framework.
(text) SELECT
[Extent1].[Applicant_ID] AS [Applicant_ID]
FROM [dbo].[W4] AS [Extent1]
This is what is displayed in the pdf textbox.
This is my query
public class Query
{
ApplicatoinContext context = new ApplicatoinContext();
public List<W4> GetId()
{
return (from p in context.w4
select new W4 { Applicant_ID = p.Applicant_ID }).ToList();
}
}
My controller
public class ApplicationController : Controller
{
// GET: Application
public ActionResult Index()
{
string template = #"c:\users\carisch\documents\visual studio 2013\Projects\Idea\Idea\fw4.pdf";
string newFile = #"c:\users\carisch\documents\visual studio 2013\Projects\Idea\Idea\Newfw4.pdf";
PdfReader reader = new PdfReader(template);
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
AcroFields fields = stamper.AcroFields;
Query num = new Query();
var query = num.GetId();
fields.SetField("f1_15_0_", query.ToString());
stamper.FormFlattening = false;
stamper.Close();
return File(#"c:\users\carisch\documents\visual studio 2013\Projects\Idea\Idea\Newfw4.pdf", "application/pdf");
}
}
I'm pretty new to programming so any help would be greatly appreciated.

How do I use OData $filter results on the server

I have a working OData controller, which supports all the normal get/put etc.
What I want to do is pass a normal odata $filter string from the client, parse and execute the filter on the server and run some code on the resulting IEnumerable.
I've messed around with ODataQueryContext, ODataQueryOptions, FilterQueryOption etc, but not really got anywhere.
Does anyone have any working examples?
Edit: I've added my function skeleton, just need to fill in the blanks
public HttpResponseMessage GetJobs(string filter)
{
*** How to convert the filter into IQueryable<Job> ***
var queryable = ?????
var settings = new ODataQuerySettings();
var jobs = queryOptions.ApplyTo(querable, settings) as IQueryable<Job>;
CsvSerializer csvSerializer = new CsvSerializer();
string csv = csvSerializer.Serialise(jobs);
string fileName = string.Format("{0} Jobs.csv", filter);
return CreateCsvResponseMessage(csv, fileName);
}
I recently had a scenario where I needed this sort of feature as well. This is what I came up with.
private static IQueryable<T> ApplyODataFilter<T>(IQueryable<T> data, string filterString) where T : class
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<T>(typeof(T).Name);
ODataQueryContext context = new ODataQueryContext(builder.GetEdmModel(), typeof(T), new ODataPath());
ODataQueryOptionParser queryOptionParser = new ODataQueryOptionParser(
context.Model,
context.ElementType,
context.NavigationSource,
new Dictionary<string, string> { { "$filter", filterString } });
FilterQueryOption filter = new FilterQueryOption(filterString, context, queryOptionParser);
IQueryable query2 = filter.ApplyTo(data, new ODataQuerySettings());
return query2.Cast<T>();
}
Try using OData code generator to generate client side code. you can following the following blog:
How to use OData Client Code Generator to generate client-side proxy class
The for the filter, the following is an example:
var q2 = TestClientContext.CreateQuery<Type>("Accounts").Where(acct => acct.Birthday > new DateTimeOffset(new DateTime(2013, 10, 1)));
There are some sample code in the codeplex to show how to do query.
Check this:
https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataQueryableSample/Program.cs
Update:
There is some sample code in the controller of the sample I gave you.
Write your code as below:
public IQueryable<Order> Get(ODataQueryOptions queryOptions)
{
if (queryOptions.Filter != null)
{
var settings = new ODataQuerySettings();
var filterResult = queryOptions.ApplyTo(OrderList.AsQueryable(), settings) as IQueryable<Order>;
// Use the filter result here.
}
}
Update 2:
You can get the raw string of the filter from ODataQueryOptions.
public IQueryable<Order> Get(ODataQueryOptions queryOptions)
{
string filterString = queryOptions.Filter.RawValue;
// Use the filterString
}
Update 3:
(Note: ODataProperties is an extension method in static class
System.Web.Http.OData.Extensions.HttpRequestMessageExtensions)
public HttpResponseMessage GetJobs(string filter)
{
var context = new ODataQueryContext(Request.ODataProperties().Model, typeof(Job));
var filterQueryOption = new FilterQueryOption(filter, context);
IQueryable<Job> queryable = GetAllJobs();
var settings = new ODataQuerySettings();
var jobs = filterQueryOption.ApplyTo(queryable, settings) as IQueryable<Job>;
CsvSerializer csvSerializer = new CsvSerializer();
string csv = csvSerializer.Serialise(jobs);
string fileName = string.Format("{0} Jobs.csv", filter);
return CreateCsvResponseMessage(csv, fileName);
}

EF4.3 Code-First, MVC, Lazy Loading After Attaching in POST Action

I'm using Entity Framework 4.3 with Code-First in an MVC 3 application. I have a POST action that gets an entity as its' parameter, and then marks the entity as modified to update the database. It's a Document entity that has a reference to a File Type.
[HttpPost]
public ActionResult Example(Document model)
{
// fileType is null, as expected
var fileType = model.FileType;
// attach and mark the entity as modified, save changes
Context.Entry(model).State = EntityState.Modified;
Context.SaveChanges();
// fileType is still null?
fileType = model.FileType;
return View(model);
}
After attaching an entity to the context, shouldn't I be able to lazy-load properties on that entity?
Interestingly, when I try this in a console application it seems to work.
static void Main()
{
// create a new context
var context = new Context();
// get the first document and detach it
var doc = context.Documents.First();
context.Entry(doc).State = EntityState.Detached;
// fileType is null, as expected
var fileType = doc.FileType;
// dispose and create a new context
context.Dispose();
context = new Context();
// attach the entity and mark it as modified
context.Entry(doc).State = EntityState.Modified;
// fileType is not null, which is the desired outcome
fileType = doc.FileType;
}
The problem is that the entity passed to the post method is not a proxy, presumably because it was created outside of the Entity Framewortk using the normal "new" operator.
There are a few options here. First, you could modify the MVC controller to create proxy instances by using the DbSet.Create method. I've heard it is possible to modify the MVC controller in this way, but never tried it myself. For example, instead of doing:
var doc = new Document();
in the controller, you would do:
var doc = context.Documents.Create();
The create method lets EF create a proxy for lazy loading, if the entity has appropriate virtual properties, which in your case it looks like it does.
A second and potentially easier option is to not use lazy loading but instead use the explicit loading APIs. For example, to load FileType:
var fileType = context.Entry(doc).Reference(d => d.FileType).Load();
Unlikely lazy loading, this needs an explicit reference to the context, but in your case that should be okay.

Resources