Get Folder Address In DLL - wpf

According This Images:
I have a folder named Gallery in Main.data Project.
I added Main.Data.Dll as reference in main project.
I want to show this images in mainwindow form.I change images build action to resource.
I want to know how can i get this folder address in main project?
in mainwindow:
private void LoadImages()
{
foreach (var imgaddress in Directory.GetFiles((Here), "*.jpg", SearchOption.AllDirectories))
{
//Do Some...
}
}
What Do i must write(Here)?

There's probably a more elegant solution, but something like this would get you the resource strings or URIs for all the jpgs in Main.Data:
private void LoadImages ()
{
var asm = Assembly.LoadFrom("Main.Data.dll");
var rm = new System.Resources.ResourceManager(asm.GetName().Name + ".g", asm);
var resourceSet = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, true, true);
var resourceUris = new List<Uri>();
var resourceStrings = new List<String>();
foreach (var resource in
resourceSet.Cast<DictionaryEntry>().Where(resource => ((string) resource.Key).EndsWith("jpg")))
{
resourceStrings.Add((string)resource.Key);
resourceUris.Add(
new Uri(String.Format("pack://application:,,,/Main.Data;component/{0}",
((string) resource.Key))));
}
rm.ReleaseAllResources();
// Do something with resourceStrings or resourceUris...
}

Related

Render AngularJs index.html in an ASP.NET Core MVC view

I'm currently working on migrating a web app with the following tech:
ASP.NET MVC
AngularJs
Gulp
Azure cloud service
to :
ASP.NET Core MVC
AngularJs
Webpack
Azure App service
The migrated app correctly bundle and serve AngularJs index.html to wwwroot.
Currently, I need to add two views to the ASP.NET Core MVC app and inject the index.html to these views.
I can't figure out how to :
Inject the index.html
Make one of the views as a startup view.
to finally have an URL pattern:
localhost/View1/#/angularJs-state
or
localhost/View2/#/angularJs-state
wwwroot :
Home :
public class BaseController : Controller
{
public IActionResult Index()
{
return View("portal");
}
}
First view :
public class PortalController : Controller
{
public IActionResult Index()
{
return View();
}
}
Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "portal",
pattern: "Portal",
defaults: new { controller = "Portal", action = "Index" });
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Base}/{action=Index}/{id?}");
});
The first view is correctly displayed but without the view name in
the url .
Is it possible to render the index.html from wwwroot in the cshtml
view using #html.Partial ?
According to your description, if you want to render the html page in the view, I suggest you could write a custom render method in mvc and return the index file as the file result to the mvc view.
More details, you could refer to below codes:
1.Create render extension method:
public static class HtmlHelperViewExtensions
{
public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, object parameters = null)
{
var controller = (string)helper.ViewContext.RouteData.Values["controller"];
return RenderAction(helper, action, controller, parameters);
}
public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, string controller, object parameters = null)
{
var area = (string)helper.ViewContext.RouteData.Values["area"];
return RenderAction(helper, action, controller, area, parameters);
}
public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)
{
if (action == null)
throw new ArgumentNullException(nameof(controller));
if (controller == null)
throw new ArgumentNullException(nameof(action));
var task = RenderActionAsync(helper, action, controller, area, parameters);
return task.Result;
}
private static async Task<IHtmlContent> RenderActionAsync(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)
{
// fetching required services for invocation
var currentHttpContext = helper.ViewContext.HttpContext;
var httpContextFactory = GetServiceOrFail<IHttpContextFactory>(currentHttpContext);
var actionInvokerFactory = GetServiceOrFail<IActionInvokerFactory>(currentHttpContext);
var actionSelector = GetServiceOrFail<IActionDescriptorCollectionProvider>(currentHttpContext);
// creating new action invocation context
var routeData = new RouteData();
var routeParams = new RouteValueDictionary(parameters ?? new { });
var routeValues = new RouteValueDictionary(new { area, controller, action });
var newHttpContext = httpContextFactory.Create(currentHttpContext.Features);
newHttpContext.Response.Body = new MemoryStream();
foreach (var router in helper.ViewContext.RouteData.Routers)
routeData.PushState(router, null, null);
routeData.PushState(null, routeValues, null);
routeData.PushState(null, routeParams, null);
var actionDescriptor = actionSelector.ActionDescriptors.Items.First(i => i.RouteValues["Controller"] == controller && i.RouteValues["Action"] == action);
var actionContext = new ActionContext(newHttpContext, routeData, actionDescriptor);
// invoke action and retreive the response body
var invoker = actionInvokerFactory.CreateInvoker(actionContext);
string content = null;
await invoker.InvokeAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
content = task.Exception.Message;
}
else if (task.IsCompleted)
{
newHttpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(newHttpContext.Response.Body))
content = reader.ReadToEnd();
}
});
return new HtmlString(content);
}
private static TService GetServiceOrFail<TService>(HttpContext httpContext)
{
if (httpContext == null)
throw new ArgumentNullException(nameof(httpContext));
var service = httpContext.RequestServices.GetService(typeof(TService));
if (service == null)
throw new InvalidOperationException($"Could not locate service: {nameof(TService)}");
return (TService)service;
}
}
2.Add controller method as below:
public IActionResult IndexFile()
{
return File("index.html", "text/html");
}
3.Add below codes into view:
#Html.RenderAction("IndexFile", "Yourcontrollername")

Angular 5 Download DOCX file from Database

I have WORD DOCX file in binary format in my SQL database.
I'm using c# WEB API controller to connect to database from get byte array and send it to my front end as string datatype.
Then trying to download it on a button click in my Angular 5 application.
Please find the code below,
WEB API Controller:
public Model testFunction()
{
byte[] inputWORDBytes = (byte[])ds.Tables[0].Rows[0][0];
Model model = new Model();
model.WORDFile = inputWORDBytes;
return model;
}
C# Model:
public class Model
{
public byte[] WORDFile { get; set; }
}
Angular Model:
export interface Model {
WORDFile : string;
}
Angular Component:
//Inside service method call
let binWord = atob(model.WORDFile);
let bytesWord = [];
for (let i = 0; i < binWord.length; i++) {
bytesWord.push(binWord.charCodeAt(i));
}
let documentWORD: Uint32Array = new Uint32Array(bytesWord);
var blob = new Blob([documentWORD], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
var url = window.URL.createObjectURL(blob);
window.open(url);
It downloads a word file but it is corrupted.

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

Telerik ComboBox with picture

I need a picture in combobox but I have only path
var files = Url.Content("~/Content/skin/Simple.png");
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(files.Select(f => new SelectListItem { Selected = false, Text = f.ToString(), Value = "" }))
)
thank you but if I need to show all pictures in folder
string searchFolder = Url.Content("~/Content/skin/");
var filters = new[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp" };
var files = Some Class.GetFilesFrom(searchFolder, filters, false);
there are my full code
controller
public ActionResult Combo()
{
return View();
}
model
public class Combo
{
public static string[] GetFilesFrom(string searchFolder, string[] filters, bool isRecursive)
{
var filesFound = new List<String>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.ToArray();
}
}
and View
#using TETRA.RS.WWW.UI.Models
#{
string searchFolder = Url.Content("~/Content/skin/");
var filters = new[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp" };
var files = Combo.GetFilesFrom(searchFolder, filters, false);
}
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(files.Select(f => new SelectListItem { Selected = false, Text = f, Value = "" }))
)
And I see only full path in combobox
And I do not Know how many pictures in a folder
There are different ways of adding images to an item selectable from a radcombobox, each has their benefits and the most suitable can only be defined by your requirements.
The easiest way is to assign a value to the ImageUrl attribute.
(Telerik Documentation: http://www.telerik.com/help/aspnet-ajax/combobox-appearance-item-images.html)
Alternatively you could modify the item template. (Telerik Demo: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/templates/defaultcs.aspx)
I have used Kendo UI
I have a folder with pictures and I don't Know how much there are
I need to get all the pictures and use in comboBox
Method finds all pictures
public static string[] GetFilesFrom(string searchFolder, string[] filters, bool isRecursive)
{
var filesFound = new List<string>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.Select(Path.GetFileName).ToArray();
}
SettingsController
public ActionResult Theme()
{
return View();
}
public JsonResult ThemeJson()
{
string searchFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content\\themes\\skin");
var filters = new[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp" };
var files = Tools.GetFilesFrom(searchFolder, filters, false);
return Json(files.Select(f => new { Id = f, Name = Path.GetFileNameWithoutExtension(f) }));
}
and View
#using Kendo.Mvc.UI
#(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { })
.DataSource(source => source.Read(read => read.Action("ThemeJson", "Settings").Type(HttpVerbs.Post)))
.Filter("startswith")
.Height(300)
.Template("<img src=\"" + Url.Content("~/Content/themes/skin/") + "${data.Id}\" alt=\"${data.Id}\" />" +
"<dl>" +
"Name theme: ${ data.Name }" +
"</dl>")
)
also you need add reference kendo.all.min.js and Kendo.Mvc.UI

How to declare array with custom indices, in Unity JavaScript?

I'm looking for a way to store variables of same type in an array, and access them by their names. Like in PHP you do:
$array = array();
$array['first member']=$var1;
$array['another member']=$var2;
// so on
I want to do a similar thing in Unity3D's JavaScript. I have AudioClip variables, currently used like this:
#pragma strict
var Audio_Goal:AudioClip;
var Audio_Miss:AudioClip;
var Audio_Saved:AudioClip;
function PlaySound_Goal()
{
audio.PlayOneShot(Audio_Goal);
}
function PlaySound_Miss()
{
audio.PlayOneShot(Audio_Miss);
}
of course this requires one function per audioclip, which is ugly.
I want to do it like this:
function PlayAudio(audioname:String)
{
audio.PlayOneShot(AudioArray[audioname]);
}
How can I do this?
You need to use something like a dictionary:
#pragma strict
import System.Collections.Generic;
var AudioArray = new Dictionary.<string,AudioClip >();
// add to dict
AudioArray["one"] = AudioClip.Create(/**/); //see AudioClip.Create(...) for arguments
// play from dict
audio.clip = AudioArray["one"];
audio.Play();
You can do something like:
var myAudioClips: AudioClip[];
function Start() {
// Your stuff...
}
function PlayAudio(audioname:String)
{
for (var myClip in myAudioClips) {
if (audioname.Equals(myClip.name)) {
audio.PlayOneShot(myClip);
}
}
}
And then add all of your clips in the array by dragging them using the editor.
You should be able to use Enumerable.Zip>, but because it's not available in UnityScript, I think this is the best you can do:
var names : List.<String>;
var clips : List.<AudioClip>;
var keyFunc = function(kvp : KeyValuePair.<String, AudioClip>) kvp.Key;
var valueFunc = function(kvp : KeyValuePair.<String, AudioClip>) kvp.Value;
var dictionary = names.Select(
function(name, index) new KeyValuePair.<String, AudioClip>(name, clips[index])
).ToDictionary(keyFunc, valueFunc);
I don't know why you need to store the Funcs. This code compiles, but won't run:
var dictionary = names.Select(
function(name, index) new KeyValuePair.<String, AudioClip>(name, clips[index])
).ToDictionary(function(kvp) kvp.Key, function(kvp) kvp.Value);
Report it as a bug if you want. I don't want to, because I don't think the devs need to waste any more time on this language.

Resources