Adding a reusable block of code in Webmatrix - layout

I have created an SQL query which checks if a user owns a record in the database, by checking if the querystring and UserID return a count of 1. This is the code below, and it works absolutely fine:
#{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var db = Database.Open("StayInFlorida");
var rPropertyId = Request.QueryString["PropertyID"];
var rOwnerId = WebSecurity.CurrentUserId;
var auth = "SELECT COUNT (*) FROM PropertyInfo WHERE PropertyID = #0 and OwnerID = #1";
var qauth = db.QueryValue (auth, rPropertyId, rOwnerId);
}
#if(qauth==0){
<div class="container">
<h1>You do not have permission to access this property</h1>
</div>
}
else {
SHOW CONTENT HERE
}
The problem is that I need to apply this check on at least 10 different pages, maybe more in the future? I'm all for using reusable code, but I'm not sure how I can write this once, and reference it on each page that it's needed. I've tried doing this in the code block of an intermediate nested layout page, but I ran into errors with that. Any suggestions as to what would be the best approach? Or am I going to have to copy and paste this to every page?

The "Razor" way is to use a Function (http://www.mikesdotnetting.com/Article/173/The-Difference-Between-#Helpers-and-#Functions-In-WebMatrix).
Add the following to a file called Functions.cshtml in an App_Code folder:
#functions {
public static bool IsUsersProperty(int propertyId, int ownerId)
{
var db = Database.Open("StayInFlorida");
var sql = #"SELECT COUNT (*) FROM PropertyInfo
WHERE PropertyID = #0 and OwnerID = #1";
var result = db.QueryValue (sql, propertyId, ownerId);
return result > 0;
}
}
Then in your page(s):
#{
Layout = "~/_SiteLayout.cshtml";
WebSecurity.RequireAuthenticatedUser();
var propertyId = Request["PropertyID"].AsInt();
var ownerId = WebSecurity.CurrentUserId;
}
#if(!Functions.IsUsersProperty(propertyId, ownerId)){
<div class="container">
<h1>You do not have permission to access this property</h1>
</div>
}
else {
SHOW CONTENT HERE
}

Related

Razor Pages: Passing query parameters in a link

I tried in the razor page:
<div>
#foreach (var cat in Model.Categories)
{
<a asp-page="/Index?catId=#cat.Id">#cat.Name</a>
}
</div>
And in the cs file:
public void OnGet()
{
CurPage = 1;
CatId = -1;
Search = "";
HasCarousel = false;
Title = "All Products";
var queryParams = Request.Query;
foreach(var qp in queryParams)
{
if (qp.Key == "curPage") CurPage = int.Parse(qp.Value);
if (qp.Key == "catId") CatId = int.Parse(qp.Value);
if (qp.Key == "search") Search = qp.Value;
if (qp.Key == "hasCarousel") HasCarousel = bool.Parse(qp.Value);
}
But when i click the link no query parameter is added to the address and the Request.Query is empty.
What am I doing wrong? Or what is the right way to pass the query parameters to a razor page via a link?
To add query parameters to your link you can use asp-route- in your a tag.
In your case it would look like
<a asp-page="Index" asp-route-catId="#cat.Id">#cat.Name</a>
You're also making receiving the query parameters in your OnGet() harder than it has to be. You can add parameters to your method signature like
OnGet(int catId)
and they will be passed in by the query parameters.

Number of items to show in Javascript

I'm using Content Search Web Part on SP 2013, I'm trying to get the value for Number of items to show option in Javascript from the ctx object. I have tried ctx.ListData.ResultTables[0].RowCount but seems like this value is for the count on the current page only, not the configured in the 'Number of items to show' option within web part configuration.
Number of items to show value in UI
In addition, do you know where can I find more information on how to debug the ctx object or the properties or methods it uses. Any help would be appreciated. Thanks in advance.
We can use JSOM to achieve it. The following code for your reference.
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(retrieveWPProperties, "sp.js");
function retrieveWPProperties(){
var pageurl=_spPageContextInfo.serverRequestPath; //current page
var currentCtx = new SP.ClientContext.get_current();
var pageFile = currentCtx.get_web().getFileByServerRelativeUrl(pageurl);
var webPartManager = pageFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webPartDefs = webPartManager.get_webParts();
currentCtx.load(webPartDefs, 'Include(WebPart.Properties)');
currentCtx.executeQueryAsync(
function () {
if (webPartDefs.get_count()) {
for (var i = 0; i < webPartDefs.get_count() ; i++) {
var webPartDef = webPartDefs.getItemAtIndex(i);
var webPart = webPartDef.get_webPart();
var properties = webPart.get_properties();
//console.log(JSON.stringify(properties.get_fieldValues())); //print all properties
if(properties.get_fieldValues().Title=="Content Search"){
var resultsPerPage=properties.get_fieldValues().ResultsPerPage;
alert(resultsPerPage);
}
}
}
else {
console.log("No web parts found.");
}
},
function (sender, args) {
console.log(args.get_message());
});
}
</script>

Bast Way On Passing Query Parameters to Solrnet

I have been working on making a Search using Solrnet which is working the way I want to. But I just would like some advice on the best way to pass my query parameters from my web page into Solrnet.
What I would ideally like to do is pass my query string parameters similar to how this site does it: http://www.watchfinder.co.uk/SearchResults.aspx?q=%3a&f_brand=Rolex&f_bracelets=Steel&f_movements=Automatic.
As you can see from the sites query string it looks like it is being passed into SolrNet directly. Here is I am doing it at the moment (facet query segment):
public class SoftwareSalesSearcher
{
public static SoftwareSalesSearchResults Facet()
{
ISolrOperations solr = SolrOperationsCache.GetSolrOperations(ConfigurationManager.AppSettings["SolrUrl"]);
//Iterate through querystring to get the required fields to query Solrnet
List queryCollection = new List();
foreach (string key in HttpContext.Current.Request.QueryString.Keys)
{
queryCollection.Add(new SolrQuery(String.Format("{0}:{1}", key, HttpContext.Current.Request.QueryString[key])));
}
var lessThan25 = new SolrQueryByRange("SoftwareSales", 0m, 25m);
var moreThan25 = new SolrQueryByRange("SoftwareSales", 26m, 50m);
var moreThan50 = new SolrQueryByRange("SoftwareSales", 51m, 75m);
var moreThan75 = new SolrQueryByRange("SoftwareSales", 76m, 100m);
QueryOptions options = new QueryOptions
{
Rows = 0,
Facet = new FacetParameters {
Queries = new[] { new SolrFacetQuery(lessThan25), new SolrFacetQuery(moreThan25), new SolrFacetQuery(moreThan50), new SolrFacetQuery(moreThan75) }
},
FilterQueries = queryCollection.ToArray()
};
var results = solr.Query(SolrQuery.All, options);
var searchResults = new SoftwareSalesSearchResults();
List softwareSalesInformation = new List();
foreach (var facet in results.FacetQueries)
{
if (facet.Value != 0)
{
SoftwareSalesFacetDetail salesItem = new SoftwareSalesFacetDetail();
salesItem.Price = facet.Key;
salesItem.Value = facet.Value;
softwareSalesInformation.Add(salesItem);
}
}
searchResults.Results = softwareSalesInformation;
searchResults.TotalResults = results.NumFound;
searchResults.QueryTime = results.Header.QTime;
return searchResults;
}
}
At the moment I can't seem to see how I can query all my results from my current code by add the following querystring: q=:.
I'm not sure what you mean by "parameters being passed into SolrNet directly". It seems that watchfinder is using some variant of the model binder included in the SolrNet sample app.
Also take a look at the controller in the sample app to see how the SolrNet parameters are built.

How to show ID field as readonly in Edit Form, of a sharepoint list?

I need to show the ID field in the Edit Form of a sharepoint list.
There is a way to do it ? I tried a calculated field and nothing.
I know that I can see the ID field in the view, and if I show as a Access Mode.
I'm using WSS3.0
You can add the ID field to the form using some JavaScript in a CEWP.
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
// Get the ID from the query string
var id = getQueryString()["ID"];
// Find the form's main table
var table = $('table.ms-formtable');
// Add a row with the ID in
table.prepend("<tr><td class='ms-formlabel'><h3 class='ms-standardheader'>ID</h3></td>" +
"<td class='ms-formbody'>" + id + " </td></tr>");
})
function getQueryString() {
var assoc = new Array();
var queryString = unescape(location.search.substring(1));
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
assoc[key[0]] = key[1];
}
return assoc;
}
</script>
There is an alternative method that doesn't use the jQuery library if you prefer to keep things lightweight.
You can do this by creating a custom edit form quite easily. I usually stick it into an HTML table rendered within a webpart. There may be a better way of doing that but it's simple and it works.
The key line you'll want to look at is spFormField.ControlMode. This tells SharePoint how to display the control (Invalid, Display, Edit, New). So what you'll want to do is check if your spField.InternalName == "ID" and if it is, set the ControlMode to be Display.
The rest is just fluff for rendering the rest of the list.
Hope this helps.
HtmlTable hTable = new HtmlTable();
HtmlTableRow hRow = new HtmlTableRow();
HtmlTableCell hCellLabel = new HtmlTableCell();
HtmlTableCell hCellControl = new HtmlTableCell();
SPWeb spWeb = SPContext.Current.Web;
// Get the list we are going to work with
SPList spList = spWeb.Lists["MyList"];
// Loop through the fields
foreach (SPField spField in spList.Fields)
{
// See if this field is not hidden or hide/show based on your own criteria
if (!spField.Hidden && !spField.ReadOnlyField && spField.Type != SPFieldType.Attachments && spField.StaticName != "ContentType")
{
// Create the label field
FieldLabel spLabelField = new FieldLabel();
spLabelField.ControlMode = _view;
spLabelField.ListId = spList.ID;
spLabelField.FieldName = spField.StaticName;
// Create the form field
FormField spFormField = new FormField();
// Begin: this is your solution here.
if (spField.InteralName == "ID")
{ spFormField.ControlMode = SPControlMode.Display; }
else
{ spFormField.ControlMode = _view; }
// End: the end of your solution.
spFormField.ListId = spList.ID;
spFormField.FieldName = spField.InternalName;
// Add the table row
hRow = new HtmlTableRow();
hTable.Rows.Add(hRow);
// Add the cells
hCellLabel = new HtmlTableCell();
hRow.Cells.Add(hCellLabel);
hCellControl = new HtmlTableCell();
hRow.Cells.Add(hCellControl);
// Add the control to the table cells
hCellLabel.Controls.Add(spLabelField);
hCellControl.Controls.Add(spFormField);
// Set the css class of the cell for the SharePoint styles
hCellLabel.Attributes["class"] = "ms-formlabel";
hCellControl.Attributes["class"] = "ms-formbody";
}
}

How to get current Item in Custom Form Action Sharepoint Designer

On custom edit page of list item, I want to do the following
- On clicking Form Action Hyperlink [DataView Control], custom form action will fire to update
a item hidden field [Status].
I already tried the following
- Passing #ID to the work flow but didnt work
- Create a duplicate ID column and updated it with the ID on Item Creation. and then tried to access in "Update Item in" Action but getting "An unexpected error has occurred" while running it.
[Remember i can only use sharepoint designer]
Try to use these javascript functions:
function GetQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
function GetCurrentItem() {
var itemId = GetQueryVariable("ID");
try {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('list-title');
this.currItem = list.getItemById(itemId);
context.load(currItem);
context.executeQueryAsync(Function.createDelegate(this, this.funcSuccess), Function.createDelegate(this, this.funcFailed));
}
catch (e) {
alert(e);
}
}
function funcSuccess() {}
function funcFailed() {}

Resources