accessing generic handler in user control cs? - c#

I have made a generic handler .ashx which is placed on root.
In my UserControls folder I have a user control which want to access this ashx class's static method. But I cannot access ashx class or its method. Does it requried any refrence or registration ?
ashx code:
<%# WebHandler Language="C#" Class="GetTileImage" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Net;
public class GetTileImage : IHttpHandler, IRequiresSessionState
{
const string c_key = "dzi";
public void ProcessRequest(HttpContext context)
{
//context.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(60));
}
public bool IsReusable
{
get
{
return true;
}
}
public static Bitmap LoadImage(string imageUrl)
{
Dictionary<string, Bitmap> images = (Dictionary<string, Bitmap>)HttpContext.Current.Session[c_key];
if (images == null)
{
images = new Dictionary<string, Bitmap>();
HttpContext.Current.Session[c_key] = images;
}
Bitmap bmp = null;
if (!images.ContainsKey(imageUrl))
{
try
{
string url = imageUrl;
if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
url = HttpContext.Current.Server.MapPath(url); WebClient wc = new WebClient(); Stream fs = wc.OpenRead(url); bmp = new Bitmap(fs); fs.Close();
}
catch { return null; }
} images.Add(imageUrl, bmp); if (images.Count > 5)
{
Dictionary<string, Bitmap>.KeyCollection.Enumerator e = images.Keys.GetEnumerator();
e.MoveNext();
string key = e.Current;
images.Remove(key);
}
return bmp;
}
}
User Control where I am accessing this:
Bitmap bmp = GetTileImage.LoadImage("");
Help plz

I don't think you'll be able to call the code from elsewhere unless you add a namespace for the class:
namespace MyNamespace
{
public class GetTileImage : IHttpHandler, IRequiresSessionState
{
// etc. etc.
}
}
MyNamespace should be replaced with whatever namespace you're using for the rest of your code.
In any case I'm a bit puzzled why this code is in an .ashx at all -- as it stands, because ProcessRequest has no code, the handler won't actually do anything.

No you can't access the Generic handler class method in code behind (aspx,ascx etc). You should have to create a static (not necessary) class (file) under App_Code folder and move this method in it.
public class GetTileImage
{
public static Bitmap LoadImage(string imageUrl)
{
..
}
}

I think this could just be because your code is in your ASHX file, if you used a code-behind file it should be fine. e.g.:
GetTileImage.ashx:
<%# WebHandler Language="C#" CodeBehind="GetTileImage.ashx.cs" Class="MyNamespace.GetTileImage" %>
GetTileImage.ashx.cs:
// < using statements here...>
namespace MyNamespace
{
public class GetTileImage: IHttpHandler
{
// < include necessary overrides... >
public static Bitmap LoadImage()
{
// < code here... >
}
}
}
You should then find you can call GetTileImage.LoadImage elsewhere in your code (tested fine here). As pointed out though already, it would be better to move the LoadImage into a utility class that both your handler and your UserControls will use.

Related

Image to byte[] (Xamarin)

I need to save an image at Parse, so I need to convert it to byte[]. Any idea how can I achieve this? I've searched for it but none of the options worked for me. I'm using a shared Xamarin Forms project. Here's an example with text :
byte[] data = System.Text.Encoding.UTF8.GetBytes("Working at Parse is great!");
ParseFile file = new ParseFile("resume.txt", data);
I'm beginner and I really need help !
[EDIT] :
For some reason, Xamarin will not let me use "System.Drawing.Image".
I've searched a lot, and I found this but I can't make it work :
public static byte[] ReadFully(System.IO.Stream input)
{
using (var ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
Thanks in advance .
If you choose images from photo gallery, you can use this codes. This codes also aim to pick up an image from photo library in iOS and save it to database as a byte array.
You said that you already have an image to display as the login form but someone who see this may not know how to get an image from your photo library in iOS so I write all of the code to archive the way to get an image and convert it to byte array.I use Prism library but any framework is ok.
If you want to only know how to convert an image to a byte array in Xamarin.forms you can go to the bottom of the codes below as MainPage class.
First, you make a new folder and name it Services. Under this folder you make an interface like this.
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.IO;
using Foundation;
namespace TestUIImage.Services
{
public interface IPicturePicker
{
Task<NSUrl> GetNSUrlAsync();
}
}
Then you write the content of GetNSUrlAsync method.
You need two methods GetNSUrl and OnImagePickerCancelled so that user select an image or cancel to select.
using System;
using System.IO;
using UIKit;
using Xamarin.Forms;
using System.Threading.Tasks;
using Foundation;
namespace TestUIImage.Services
{
public class PicturePickerImplementation : IPicturePicker
{
public PicturePickerImplementation()
{
}
TaskCompletionSource<NSUrl> urltaskCompletionSource;
UIImagePickerController imagePicker;
public Task<NSUrl> GetNSUrlAsync()
{
// Create and define UIImagePickerController
imagePicker = new UIImagePickerController
{
SourceType = UIImagePickerControllerSourceType.PhotoLibrary,
MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary)
};
// Set event handlers
imagePicker.FinishedPickingMedia += GetNSUrl;
imagePicker.Canceled += OnImagePickerCancelled;
// Present UIImagePickerController
UIWindow window = UIApplication.SharedApplication.KeyWindow;
var viewController = window.RootViewController;
viewController.PresentModalViewController(imagePicker, true);
// Return Task object
urltaskCompletionSource = new TaskCompletionSource<NSUrl>();
return urltaskCompletionSource.Task;
}
void GetNSUrl(object sender, UIImagePickerMediaPickedEventArgs args)
{
urltaskCompletionSource.SetResult(args.ImageUrl);
imagePicker.DismissModalViewController(true);
}
void OnImagePickerCancelled(object sender, EventArgs args)
{
taskCompletionSource.SetResult(null);
imagePicker.DismissModalViewController(true);
}
}
}
Next, you register your services using DependencyService because selecting an image from your photo gallery in iOS depends on your platform.
using Prism;
using Prism.Ioc;
using TestUIImage.ViewModels;
using TestUIImage.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Prism.Autofac;
using TestUIImage.Services;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace TestUIImage
{
public partial class App : PrismApplication
{
public App() : this(null) { }
public App(IPlatformInitializer initializer) : base(initializer) { }
protected override async void OnInitialized()
{
InitializeComponent();
DependencyService.Register<PicturePickerImplementation>();
await NavigationService.NavigateAsync("NavigationPage/MainPage");
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<MainPage>();
}
}
}
Then, you add this code in Info.plist because of the iOS security.
...
<key>NSPhotoLibraryUsageDescription</key>
<string>Picture Picker uses photo library</string>
</dict>
</plist>
Finally, you can call your services in codebehind. In this time, I used Image controller as TestImage and Button controller as PickPictureButton.
using System;
using System.IO;
using System.Drawing;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Foundation;
using Xamarin.Forms;
using TestUIImage.Services;
namespace TestUIImage.Views
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
async void Handle_Clicked(object sender, System.EventArgs e)
{
PickPictureButton.IsEnabled = false;
NSUrl nSUrl = await DependencyService.Get<IPicturePicker>().GetNSUrlAsync();
TestImage.Source = ImageSource.FromStream(() =>
{
var ms = new MemoryStream();
var imagebytes = File.ReadAllBytes(nSUrl.Path);
ms.Write(imagebytes, 0, imagebytes.Length);
ms.Seek(0, SeekOrigin.Begin);
return ms;
});
PickPictureButton.IsEnabled = true;
}
}
}
Here's some code to convert a BitmapImage to a byte[]:
public byte[] ConvertToBytes(BitmapImage bitmapImage)
{
if (bitmapImage != null)
{
MemoryStream memStream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(memStream);
return memStream.GetBuffer();
}
return null;
}
Here's some code to convert a byte[] to a BitmapImage:
private void LoadImage()
{
var image = Services.GetImage(_employeeID);
if (image.Image != null)
{
MemoryStream strmImg = new MemoryStream(image.Image);
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.Image = myBitmapImage;
}
}
This has worked for me many times.

want to access data from text box in the form which is in another solution in visual studio 2013?

I have two solutions TranferService and Sender. TranferService has WCF service and IISHost to host that service. In Sender solution i have windows forms application. In that form i used button to browse and select file, text box to display selected file path, and another button(Send) to transfer that file through WCF service. But i am unable to access textbox value in the transfer solution. it shows"the name does not exist in the current context".
Code for TransferService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TransferService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TransferService" in both code and config file together.
public class TransferService : ITransferService
{
public File DownloadDocument()
{
File file = new File();
String path = txtSelectFilePath.Text;
file.Content = System.IO.File.ReadAllBytes(#path);
//file.Name = "ImagingDevices.exe";
return file;
}
}
}
I am getting error on this line
String path = txtSelectFilePath.Text;
code for form.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sender
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Browse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtSelectFilePath.Text = openFileDialog1.FileName;
}
}
private void Send_Click(object sender, EventArgs e)
{
TransferService.TransferServiceClient client = new TransferService.TransferServiceClient();
TransferService.File file = client.DownloadDocument();
System.IO.File.WriteAllBytes(#"C:\DownloadedFiles\" + file.Name, file.Content);
MessageBox.Show(file.Name + " is downloaded");
}
}
}
Code for ITransferService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TransferService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ITransferService" in both code and config file together.
[ServiceContract]
public interface ITransferService
{
[OperationContract]
File DownloadDocument();
}
[DataContract]
public class File
{
[DataMember]
public string Name { get; set; }
[DataMember]
public byte[] Content { get; set; }
}
}
Thanx a lot in advance..........
Then create a constructor to your class that receives a path as string something like this:
public class TransferService : ITransferService
{
private string _path;
public TransferService(string path) {
_path = path
}
public File DownloadDocument()
{
File file = new File();
//String path = txtSelectFilePath.Text;
file.Content = System.IO.File.ReadAllBytes(_path);
//file.Name = "ImagingDevices.exe";
return file;
}
}
and then on form.cs
TransferService.TransferServiceClient client = new TransferService.TransferServiceClient(txtSelectFilePath.Text);

using variables from another file .cs

I have a project in c# winforms, with a file called: PublicSettings.cs (this file is within a folder called: Class) where I have a variable.
Now, I want to use that variable from another file within the same project.
PublicSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LVSetup.Class
{
class PublicSettings
{
private string _ConnStr = "Connection";
public string ConnStr
{
get
{
return this._ConnStr;
}
set
{
this._ConnStr = value;
}
}
}
}
I want to use the variable ConnStr in the file: frmLogin.cs
frmLogin.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LVSetup.Class;
namespace LVSetup
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
string a = PublicSettings.ConnStr;
}
}
}
But there is no ConnStr within PublicSettings, just (Equals and ReferenceEquals)
What could be wrong here?
You need to make this field static in order to access it without creating a class instance. Or create and instance. What suites the best depends on the logic that you want to apply for this class and how it will be used later.
Instance approach
private void btnEnter_Click(object sender, EventArgs e)
{
var settings = new PublicSettings();
string a = settings.ConnStr;
}
Static field approach
class PublicSettings
{
private static string _ConnStr = "Connection";
public static string ConnStr
{
get
{
return _ConnStr;
}
set
{
_ConnStr = value;
}
}
}
For a connection string, I would either use a Configuration file (app.config) or make the property a static read-only property (since there's often no reason to change a connection string at run-time):
class PublicSettings
{
public static string ConnStr
{
get
{
return "Connection";
}
}
}

Awesomium not loading page or triggering any events

I want to do something a simple as loading a webpage. For some reason Awesomium is not updating properties such as IsLoading, or triggering events such as DocumentReady or LoadingFrameComplete and I have no idea why, can anyone help me out?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
namespace DownloaderTest
{
class ParsingHelper
{
WebView wv;
public ParsingHelper(WebView web)
{
this.wv = web;
}
public void ParsingInitiation(string link)
{
wv.LoadingFrameComplete +=wv_LoadingFrameComplete;
wv.Source = new Uri(link);
}
void wv_LoadingFrameComplete(object sender, FrameEventArgs e)
{
if(e.IsMainFrame)
{
//BeginParsing
((WebView)sender).LoadingFrameComplete -= wv_LoadingFrameComplete;
}
}
}
class Teste
{
WebView MainWeb = WebCore.CreateWebView(1024,768);
public object[] ObtainInformation(int id)
{
ParsingHelper ph = new ParsingHelper(MainWeb);
ph.ParsingInitiation("http://www.google.com");
//More code
return new object[] {};
}
}
}
If I run something like...
Teste t = new Teste();
t.ObtainInformation(1);
wv_LoadingFrameComplete is never triggered and I have no idea why.
try this code to detect page loaded completely
loadingFrameCompete event + IsLoading property
private void Awesomium_Windows_Forms_WebControl_LoadingFrameComplete(object sender, Awesomium.Core.FrameEventArgs e)
{
if (!webControl1.IsLoading)
MessageBox.Show("Page Loaded Completely");
}
Answered here: http://answers.awesomium.com/questions/2260/awesomium-not-loading-page-or-triggering-any-event.html
You are either using Awesomium in non UI environment (not WPF/WinForms control) and must call WebCore.Update() implicitly or you just blocking the same thread so it can't fire events.

Can't figure out why I dont have access to a public function in a separate class

I am trying to call a public function inside a public class in my web application but for some reason the function is not accessible even though I can get to the class fine and the function is marked as public. When I call FileUploader, the only options I am given are equals and referanceequals. What stupid thing am I over looking? Please not that the class is in a secondary project called Classes in my app. I do not have problems accessing a difference class in the project that FileUploader is in.
using System;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;
using System.IO;
using System.Configuration;
using FFInfo.Classes;
namespace FFInfo
{
public partial class FUTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fuFile.HasFile)
{
}
}
}
}
FileUploaders.cs
using FFInfo.DAL;
using FFInfo.DAL.Tables;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Web;
namespace FFInfo.Classes
{
public class FileUploader
{
public Int64 UploadSiteImage(string ConnectionString, string ContainerName, string FilePath, HttpPostedFile UploadedFile)
{
CloudStorageAccount SiteImages = CloudStorageAccount.Parse(ConnectionString);
CloudBlobClient SiteImagesBlob = SiteImages.CreateCloudBlobClient();
CloudBlobContainer SiteImageContainer = SiteImagesBlob.GetContainerReference(ContainerName);
SiteImageContainer.CreateIfNotExists();
CloudBlockBlob Image = SiteImageContainer.GetBlockBlobReference(FilePath + UploadedFile.FileName);
using (UploadedFile.InputStream)
{
Image.UploadFromStream(UploadedFile.InputStream);
}
using (var db = new Compleate())
{
File NewFile = new File()
{
ContainerName = ContainerName,
FilePath = FilePath,
FileName = UploadedFile.FileName,
ContentType = UploadedFile.ContentType
};
db.Files.Add(NewFile);
db.SaveChanges();
return NewFile.FileID;
}
}
}
}
Did you perhaps mean for the UploadSiteImage method to be static?
Try (new FileUploader()). <-- will get intelisense here.
But, yeah, you probably want the method to be public static

Categories

Resources