|
the post about out of process session state is interesting. still need time to digust the topic as I am not familar with it at all. I believe I have a basic idea how to go about doing this now. thanks again for the help!
|
|
|
|
|
You should separate the database code from the controllers and views. I created a database class implementing an interface that is passed to the controllers, providing methods to obtain the required data from the database. Thus there is a minimal common interface between the web site and the database code, and the web site knows nothing about the database. This allows testing of the database code with a desktop test harness. It also allows easy replacement of the database code if for example I change database provider.
I used Dapper for database access, but PetaPoco is better IMO.
|
|
|
|
|
hi Leif Simon Goodwin,
Yes, I believe that calling into an webapi is better in terms of separation of concern, and I have started doing that for my project. I've never heard of petapoco before and it looks interesting. I am just using good old ADO.NET using queries and loading data to POCOs.
|
|
|
|
|
|
I used to use Entity Framework. Everything seemed to work well enough to get me hooked, until there are more complicated examples, such as pull fields from different tables using a stored procedure and try to update the fields in the object afterwards, that will get me all the time ...
|
|
|
|
|
hi all,
I am going to build an asp.net core website and an asp.net core webapi. My question is that from design perspective, should I just call into the webapi to get data for my website? or just call into the database to get data directly?
It looks like calling the webapi would promote separation of concerns and I don't have to expose my database connection strings in multiple places, but I am afraid there is a performance hit that will impact the performance of the load time of the website.
Any insight is greatly appreciated.
|
|
|
|
|
I am new to PHP programming and I am trying to teach myself WordPress theme development for fun and I am using PhpStorm as my IDE.
I am trying to better understand the inner-workings of WordPress and I am running into a roadblock on something.
I have a sandbox plugin that I created to use to play around with WordPress.
In my wp-content/plugins/sandbox/sandbox.php file, I am just running basic PHP code to help me get used to the language as it relates to WordPress.
Also, I installed both Kint and Whoops using Composer to help with debugging.
Now that I got that out of the way, here is what I am doing:
Code #1
namespace MyDevPlayground\Sandbox;
add_action( 'loop_start', __NAMESPACE__ . '\process_the_string' );
function process_the_string() {
$current_user = wp_get_current_user();
$data_packet = array(
'id' => $current_user->ID,
'email' => $current_user->user_email,
'name' => array(
'first_name' => $current_user->user_firstname,
'last_name' => $current_user->user_lastname,
),
);
render_user_message( $data_packet );
}
function render_user_message( array $current_user ) {
$user_id = $current_user['id'];
d( "Welcome {$current_user['name']['first_name']}, your user id is { {$user_id} }." );
ddd( "Welcome {$current_user['name']['first_name']}, your user id is {$user_id}." );
}
When I run Code #1 above everything is fine and Kint displays the values just fine.
Now for the problem I am having that I don’t understand about WordPress:
Code #2
<pre lang="PHP">namespace MyDevPlayground\Sandbox;
add_action( 'loop_start', __NAMESPACE__ . '\check_logged_in_user' );
function check_logged_in_user(){
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) {
d('Not logged in');
} else {
ddd('Logged in');
}
}
check_logged_in_user();
When I run Code #2 above, Whoops reports the following error:
Call to undefined function MyDevPlaygroundSandbox\wp_get_current_user
For some reason when I run Code #1, the wp_get_current_user() function loads just fine, but not with Code #2.
Can someone help me understand why this is in laymen’s terms if possible?
What is the difference between Code #1 and Code #2?
How come the wp_get_current_user() function is not loading in Code #2, but it is in Code #1?
Thank you for your help.
|
|
|
|
|
I'm working on a RestSharp wrapper class. I can call the API and step into the controller. The controller creates the response data and returns it. However, when I get the entity back from the API its properties are not set.
Controller
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("application/json"));
}
}
public class CustomerController : ApiController
{
[HttpGet]
public APIResponse<CustomerEntity> GetCustomer(int id)
{
var response = new APIResponse<CustomerEntity>
{
Success = true
};
try
{
var data = new CustomerEntity
{
Id = 1,
CustomerName = "ACME Widgets"
};
response.Result = data;
}
catch (Exception e)
{
var rm = new ReponseMessage
{
Exception = e,
Message = e.Message
};
response.Messages.Add(rm);
}
return response;
}
}
RestSharp Wrapper
public class APIExecutor
{
#region Private Fields
private RestClient client;
private RestRequest request;
private string baseURL;
#endregion
public APIExecutor(string url, Method method = Method.POST)
{
baseURL = "<a href="http:
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("Url");
}
client = new RestClient(baseURL);
client.AddHandler("application/json", () => { return new JsonDeserializer(); });
request = new RestRequest(url, method)
{
RequestFormat = DataFormat.Json
};
}
public async Task<APIResponse<T>> ExecuteAsync<T>()
{
IRestResponse<T> response = await client.ExecuteAsync<T>(request);
var results = new APIResponse<T>
{
StatusCode = response.StatusCode,
RequestURL = response.ResponseUri.ToString()
};
if (response.StatusCode == HttpStatusCode.OK)
{
results.Success = true;
results.Result = response.Data;
return results;
}
else
{
var exception = LogError(new Uri(baseURL), request, response);
var message = new ReponseMessage
{
Message = response.StatusDescription,
Exception = exception
};
results.Messages.Add(message);
results.Success = false;
}
return results;
}
}
The response content does not look like JSON. I'm wondering if either the WebApiConfig or RestClient.AddHandler is wrong.
I could some expert eyes on this. Not sure why deserialization isn't working.
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
modified 9-Nov-20 14:20pm.
|
|
|
|
|
Your API returns APIResponse<T> . Your client seems to be looking for a response of type T . I suspect this mismatch is what's causing the problem.
Kevin Marois wrote: The response content does not look like JSON.
What does it look like?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: What does it look like?
This is what the response content looks like:
{"<messages>k__BackingField":[],"<statuscode>k__BackingField" ,"<requesturl>k__BackingField":null,"<result>k__BackingField":{"<id>k__BackingField":1,"<customername>k__BackingField":"ACME Widgets"},"<success>k__BackingField":true}
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
That's definitely an APIResponse<CustomerEntity> rather than a CustomerEntity .
It looks like a problem with your JSON formatter - it's serializing the fields instead of the properties. All of those mangled names are what the compiler generates to store the values for auto-implemented properties[^].
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: That's definitely an APIResponse<CustomerEntity> rather than a CustomerEntity .
It looks like a problem with your JSON formatter - it's serializing the fields instead of the properties
Agreed. What can I do about it? Maybe a custom JSON formatter?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
From what I can tell, this appears to be a server-side problem. If I type the URL into a browser, I get back the same format I posted earler. It's clearly not JSON.
Here's my WebAPIConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
}
Other than this, I'm not reallt sure what else to look for. I'm open to ideas.
Thanks
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
|
Richard Deeming wrote: Are your classes marked as [Serializable] ? You may need to add [DataContract] to the class and [DataMember] to the properties.
Yes, I had the [Serializable] attribute, but not the others. I look at that twice and just didn't see it. Too many late nights
It seems to work OK now. Thank you for all your help.
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
I'm trying to make an add-on for Firefox that will store some values which will be used later on in an contextMenus.
Getting the value and setting a new one in options_ui works just fine. The problem is when I try to get the value by using the new contextMenu I am adding in background.js. The new contextMenu it is added, the window for saving the file appers, but the value from storage returns undefined. Can anyone help me with this, point me where I'm doing something wrong?
I am setting a new value before using the contextMenu.
background.js
var gettingValue = browser.storage.sync.get("number");
gettingValue.then(item =>{
browser.contextMenus.create({
id: "save-image",
title: "Save image",
contexts: ["image"],
});
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "save-image") {
let name = "Initial";
if(item) {
name = item.number;
} else {
name = "Number not found";
}
browser.downloads.download({
url : info.srcUrl,
filename : name + ".jpg",
saveAs : true
});
}
});
});
options.js
function saveOptions(e) {
e.preventDefault();
browser.storage.sync.set({
number: document.querySelector("#newNumber").value
});
}
function restoreOptions() {
let getting = browser.storage.sync.get("number");
getting.then(setCurrentChoice, onError);
function setCurrentChoice(result) {
document.querySelector("#newNumber").value = result.number || "No number was set";
}
function onError(error) {
console.log(`Error: ${error}`);
}
}
document.addEventListener("DOMContentLoaded", restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
options.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form>
<label>Number input: <input type="text" id="newNumber" ></label>
<button type="submit">Save</button>
</form>
<script src="options.js"></script>
</body>
</html>
Permissions in manifest
"permissions": [
"contextMenus",
"downloads",
"storage"
],
modified 4-Nov-20 9:02am.
|
|
|
|
|
Solution:
browser.contextMenus.create({
id: "save-image",
title: "Save image",
contexts: ["image"],
});
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "save-image") {
var gettingValue = browser.storage.sync.get("number");
gettingValue.then(item =>{
let name = "Initial";
if(item) {
name = item.number;
} else {
name = "Number not found";
}
browser.downloads.download({
url : info.srcUrl,
filename : name + ".jpg",
saveAs : true
});
});
}
});
|
|
|
|
|
Could anybody help me to explain this block code, i knew that is callback hell and try to imagine short and simple but i can not
Thanks alot
--------------------------
function getAll() {
getName("Hoa",function(){
getName("Moc",function(){
getName("Lan",function(){
getName("Duy",function(){
})
})
})
})
}
function getName(name, cb){
setTimeout(
function() {
console.log(name);
cb();
}, 1000
)
}
getAll();
|
|
|
|
|
Start by using Promises:
Using Promises - JavaScript | MDN[^]
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
function getName(name) {
return wait(1000).then(() => console.log(name));
}
function getAll(){
getName("Hoa")
.then(() => getName("Moc"))
.then(() => getName("Lan"))
.then(() => getName("Duy"));
} Demo[^]
Support is pretty good in everything except Internet Explorer.
If you want to make it even cleaner, consider using an async function:
async function - JavaScript | MDN[^]
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function getName(name) {
await wait(1000);
console.log(name);
}
async function getAll(){
await getName("Hoa");
await getName("Moc");
await getName("Lan");
await getName("Duy");
} Demo[^]
Again, support is pretty good for everything except Internet Explorer.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Dear all
could anybody help me with image in the red frame. When i remove 2 images, the image work perfectly with perfectly circle, but when I add more two pictures, the circle transform into the oval.
Could anybody help me to keep remain the circle, if i add more pictures, it can be hidden or appear half or quarter is fine with me.
here is my code: https://jsfiddle.net/n6fb9xtr
thanks alot
|
|
|
|
|
Hi all
Could anybody tell me why this code block css:
.img-bcg {
height: calc(100vh -77.8px);
background: url("https://unsplash.com/photos/Q0mDOn9gWk8") center/cover no-repeat;
} not working in my project below.
https://jsfiddle.net/hu5s3c7o/
thank alot
|
|
|
|
|
Two problems:
- Your height property is invalid. You need a space between the
- and the 77.8px . - You've specified the URL of the HTML page containing the image, not the image itself. HTML pages cannot be used as background images.
Change your style to:
.img-bcg {
height: calc(100vh - 77.8px);
background: url("https://images.unsplash.com/photo-1510662179966-f3e62f0fb4fe?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1650&q=80") center/cover no-repeat;
} Updated demo[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
It works perfectly,
thanks alot
|
|
|
|
|
Hello:
Windows 10 workstation
Apache 2.4
PHP 7.2.
I've installed Apache and PHP on a Windows 10 workstation and everything (including PHP) works beautifully. But when I change the documentroot in the http.conf file, Apache stops sending .php files to the PHP engine. Apache opens the .php files in the new directory, but the <?php> code no longer gets parsed and processed by the php engine (php.exe). Apache no longer runs those files through the php module.
Here is what I've changed in the http.conf file:
OLD SETTING:
DocumentRoot "${SRVROOT}/htdocs"
<Directory "${SRVROOT}/htdocs">
NEW SETTING:
DocumentRoot "C:/WWW"
<Directory "C:/WWW">
When I change it back again, PHP works just fine.
I've also tried changing the doc_root setting in php.ini, but that doesn't help. Apache loads the .php page, but never sends it to the php server.
Any thoughts or help?
Thanks!
|
|
|
|
|
Somewhere else in your httpd.conf there will be some configuration that makes PHP work. Search the file for "php" and see what you can find, then check that it isn't in its own <Directory> group or something similar.
If you can't find anything about PHP in the main file, look for Include lines - the httpd.conf can include other files, so you might have one that is specific to PHP.
The php.ini file is read by PHP itself, and it doesn't sound like it is getting that far.
|
|
|
|