Displaying image in web application - c#

i have problem with displaying image in my web app. It took photo from database, and should dispay in web app.
protected void btnShowPhoto_Click(object sender, EventArgs e)
{
string adresURL = #"~/Content";
string camPath = "";
string[] tab = new string[10];
CheckBox[] _boxes = new CheckBox[] { this.CheckBox1, this.CheckBox2, this.CheckBox3, this.CheckBox4, this.CheckBox5, this.CheckBox6, this.CheckBox7, this.CheckBox8 };
System.Web.UI.WebControls.Image[] _images = new System.Web.UI.WebControls.Image[] { this.Image1, this.Image2, this.Image3, this.Image4, this.Image5, this.Image6, this.Image7, this.Image8 };
Label[] _labels = new Label[] { this.lblCameraName1, this.lblCameraName2, this.lblCameraName3, this.lblCameraName4, this.lblCameraName5, this.lblCameraName6, this.lblCameraName7, this.lblCameraName8 };
System.Web.UI.HtmlControls.HtmlAnchor[] _linkscontrol = new System.Web.UI.HtmlControls.HtmlAnchor[] { this.imagelink1, this.imagelink2, this.imagelink3, this.imagelink4, this.imagelink5, this.imagelink6, this.imagelink7, this.imagelink8 };
for (int i = 0; i < 8; i++)
{
_images[i].Visible = false;
_labels[i].Visible = false;
_linkscontrol[i].HRef = "";
}
for (int i = 0; i < 8; i++)
{
if (_boxes[i].Checked)
{
camPath = null;
tab = null;
camPath = this.GridView2.Rows[i].Cells[0].Text;
tab = camPath.Split(new string[] { "StoredPhotos" }, StringSplitOptions.None);
//Virtual Path'a
camPath = adresURL + tab[1].Replace(#"\", "/");
_labels[i].Visible = true;
_labels[i].Text = this.GridView2.Rows[i].Cells[1].Text;
_linkscontrol[i].HRef = camPath;
_images[i].ImageUrl = camPath;
_images[i].Visible = true;
}
else
_images[i].Visible = false;
}
}
I have problem with my virtual path probably. CamPath(Virtual Path) becomes from : E:\Photo\StoredPhotos\20151010\000003819619_201512021335_1_C1, and finally looks: ~/20151010/000003819619_201512021335_1_C1

This path means nothing to a web browser:
~/20151010/000003819619_201512021335_1_C1
It doesn't know what to do with that ~ directory. That's a server-side concept, not a client-side concept. So your server-side code needs to resolve that to an actual path.
It could be as simple as just explicitly starting from the root of the server:
string adresURL = #"/Content";
So the resulting URL would start with /Content/..... and the browser would check for the image in that path.
But if the application isn't (or might not be) the root of the server domain then you'd need to either manually account for that or use a server-side helper of some sort. There are a variety of ways to go about that, for example:
_images[i].ImageUrl = System.Web.VirtualPathUtility.ToAbsolute(camPath);

The browser expect access to image via http protocol, if you want view the image you have 2 diffrerent way:
(simple) Create a virtual directory under iis that point to a phisical folder E:\Photo\StoredPhotos\ and called StoredPhotos, in _images[i].ImageUrl you may set the value /StoredPhotos/20151010/000003819619_201512021335_1_C1.jpg
(complex) Build a class that read the file on the disk and write it to the response (use IHttpHandler interface), add this handler to web.config and set _images[i].ImageUrl the value of 'NameOfHandler.aspx?20151010/000003819619_201512021335_1_C1

Related

Pin Application to Taskbar using C#

I have searched for this same topic and I found the solution. But the problem is the NameSpace property is giving exception. I have tried with this code :
public bool PinUnpinTaskbar(string filePath, bool pin)
{
if (!File.Exists(filePath)) throw new FileNotFoundException(filePath);
int MAX_PATH = 255;
var actionIndex = pin ? 5386 : 5387; // 5386 is the DLL index for"Pin to Tas&kbar", ref. http://www.win7dll.info/shell32_dll.html
//uncomment the following line to pin to start instead
//actionIndex = pin ? 51201 : 51394;
StringBuilder szPinToStartLocalized = new StringBuilder(MAX_PATH);
IntPtr hShell32 = LoadLibrary("Shell32.dll");
LoadString(hShell32, (uint)actionIndex, szPinToStartLocalized, MAX_PATH);
string localizedVerb = szPinToStartLocalized.ToString();
string path = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
// create the shell application object
//var shell = new Shell32.Shell();
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
dynamic directory = shellApplication.NameSpace(path);
dynamic link = directory.ParseName(fileName);
dynamic verbs = link.Verbs();
for (int i = 0; i < verbs.Count(); i++)
{
dynamic verb = verbs.Item(i);
if (verb.Name.Equals(localizedVerb))
{
verb.DoIt();
return true;
}
}
return false;
}
But the problem is with shellApplication.Namespace(path) here. It can not find such property/Method. I don't have too much idea on this. So, any kind of help will be appreciated.

Telerik Report in Asp.Net-Apply Filters in programatically

My Requirement: Apply fillers via c# coding(Not Design) ie, filterer salaries greater than 7000.
I have a class library and a web form in my project.
I am creating the report on class library and display report by using web form.
When I run my application it shows always the unfiltered data.
What i do to get Filtered data in Viewer.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Telerik.Reporting.Filter f1 = new Telerik.Reporting.Filter();
f1.Expression = "= Fields.Salary";
f1.Operator = Telerik.Reporting.FilterOperator.GreaterOrEqual;
f1.Value = "=7000";
EmpReport objEmpReport = new EmpReport(); objEmpReport.Filters.Add(f1);
TypeReportSource rptSource = new TypeReportSource(); rptSource.TypeName = typeof(EmpReport).AssemblyQualifiedName; this.ReportViewer1.ReportSource = rptSource;
}
}
working code:
// ...
using Telerik.Reporting;
using Telerik.Reporting.Processing;
// ...
void ExportToPDF(string reportToExport)
{
// all my reports are in trdx format - detect file type and use unpackage below for trdp files.
string currPath = HttpRuntime.AppDomainAppPath; // get the full path so deserialise works
reportToExport = currPath + #"Reports\" + reportToExport; // add folder and report name to path
UriReportSource uriReportSource = new UriReportSource { Uri = reportToExport }; // compressed to 1 line for brevity
Telerik.Reporting.Report myReport = DeserializeReport(uriReportSource); // extract report from xml format (trdx)
// Filters are client side (use params for server side) Here we work with the report object.
// set meaningful field name and values for your code, maybe even pass in as params to this function...
myReport.Filters.Add("UserId", FilterOperator.Equal , "1231");
var instanceReportSource = new Telerik.Reporting.InstanceReportSource(); // report source
instanceReportSource.ReportDocument = myReport; // Assigning Report object to the InstanceReportSource
// kinda optional, lots of examples just used null instead for deviceInfo
System.Collections.Hashtable deviceInfo = new System.Collections.Hashtable(); // set any deviceInfo settings if necessary
ReportProcessor reportProcessor = new ReportProcessor(); // will do work
RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, deviceInfo); // GO!
if (!result.HasErrors)
{
this.Response.Clear();
this.Response.ContentType = result.MimeType;
this.Response.Cache.SetCacheability(HttpCacheability.Private);
this.Response.Expires = -1;
this.Response.Buffer = true;
this.Response.BinaryWrite(result.DocumentBytes);
this.Response.End();
}
else
{
Exception[] ex = result.Errors;
throw new Exception(ex[0].Message);
}
}
Telerik.Reporting.Report DeserializeReport(UriReportSource uriReportSource)
{
var settings = new System.Xml.XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (var xmlReader = System.Xml.XmlReader.Create(uriReportSource.Uri, settings))
{
var xmlSerializer = new Telerik.Reporting.XmlSerialization.ReportXmlSerializer();
var report = (Telerik.Reporting.Report)xmlSerializer.Deserialize(xmlReader);
return report;
}
}
Telerik.Reporting.Report UnpackageReport(UriReportSource uriReportSource)
{
var reportPackager = new ReportPackager();
using (var sourceStream = System.IO.File.OpenRead(uriReportSource.Uri))
{
var report = (Telerik.Reporting.Report)reportPackager.UnpackageDocument(sourceStream);
return report;
}
}

wix # script for creating a installer

I have a wpf application which helps user to selects the directory path and when he click create installer button then I want to create installer for user selected directory(inside directory there may me more than one file).
I came to know that I can use a wix# script and then I call this script when button is clicked. But I don't know how to write a wix# script which take input for file (the file for that installer is going to create).
I am familier with basic wix and new to wix #. Please help me to solve my problem.
You could try the Wixsharp solution.
You can get it from the nuget reference option (Visual studio), then you just need to write the code so it works like you want it.
I'll make a C# example:
static string sRootDir = #"<Path of Source directory>";
static void BuildMSI()
{
WixEntity[] weDir = new WixEntity[0];
weDir = BuildDirInfo(sRootDir, weDir);
var project = new Project("My product", weDir)
{
GUID = Guid.NewGuid(),
//UI = WUI.WixUI_InstallDir,
Version = new Version(55, 0, 0, 0),
UpgradeCode = guidUpgradeCode, // Forwarded if upgrading existing product
MajorUpgradeStrategy = new MajorUpgradeStrategy
{
UpgradeVersions = VersionRange.OlderThanThis,
PreventDowngradingVersions = VersionRange.NewerThanThis,
NewerProductInstalledErrorMessage = "Newer version already installed"
}
};
project.BuildMsi(project);
}
static WixEntity[] BuildDirInfo(string sRootDir, WixEntity[] weDir)
{
DirectoryInfo RootDirInfo = new DirectoryInfo(sRootDir);
if (RootDirInfo.Exists)
{
DirectoryInfo[] DirInfo = RootDirInfo.GetDirectories();
List<string> lMainDirs = new List<string>();
foreach (DirectoryInfo DirInfoSub in DirInfo)
lMainDirs.Add(DirInfoSub.FullName);
int cnt = lMainDirs.Count;
weDir = new WixEntity[cnt + 1];
if (cnt == 0)
weDir[0] = new DirFiles(RootDirInfo.FullName + #"\*.*");
else
{
weDir[cnt] = new DirFiles(RootDirInfo.FullName + #"\*.*");
for (int i = 0; i < cnt; i++)
{
DirectoryInfo RootSubDirInfo = new DirectoryInfo(lMainDirs[i]);
if (!RootSubDirInfo.Exists)
continue;
WixEntity[] weSubDir = new WixEntity[0];
weSubDir = BuildDirInfo(RootSubDirInfo.FullName, weSubDir);
weDir[i] = new Dir(RootSubDirInfo.Name, weSubDir);
}
}
}
return weDir;
}

Creating User in dotnetnuke and Assign Role using c#

I'm trying to create a user programatically using C# in dnn. When ever I execute the code below, it throws object reference error. I tried breaking the code and I found out that its not getting inside the if (result == UserCreateStatus.Success) statement. Whenever I point my mouse to the result instant, it shows an invalid password message. The thing is that I have used this same code before somewhere else and its working fine. I even copied what I used earlier on but its keeps showing the same error. Please is there anything I'm missing?
//Generating 8 char passwor
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c = Convert.ToChar(adomRng.Next(48, 128))).ToString(), "[A-Za-z0-9]")) ;
rndString += c;
}
string space = " ";
UserInfo oUser = new UserInfo();
oUser.PortalID = this.PortalId;
oUser.IsSuperUser = false;
oUser.FirstName = Session["fname"].ToString();
oUser.LastName = Session["lname"].ToString();
oUser.Email = Session["email"].ToString();
oUser.Username = Session["username"].ToString();
oUser.DisplayName = Session["fname"].ToString() + space.ToString() + Session["lname"].ToString();
//Fill MINIMUM Profile Items (KEY PIECE)
oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage;
//oUser.Profile.PreferredTimeZone =PortalSettings.TimeZoneOffset;
oUser.Profile.FirstName = oUser.FirstName;
oUser.Profile.LastName = oUser.LastName;
//Set Membership 17:
UserMembership oNewMembership = new UserMembership();
oNewMembership.Approved = true;
oNewMembership.CreatedDate = System.DateTime.Now;
oNewMembership.Email = oUser.Email;
oNewMembership.IsOnLine = false;
oNewMembership.Username = oUser.Username;
oNewMembership.Password = rndString;
UserCreateStatus result = UserController.CreateUser(ref oUser);
if (result == UserCreateStatus.Success)
{
RoleController oDnnRoleController = new RoleController();
//Get the role information
RoleInfo oCurrentRole = oDnnRoleController.GetRoleByName(this.PortalId, Request.QueryString["TSORole"].ToString());
// RoleInfo oCurrentRole1 = oDnnRoleController.GetRoleByName(this.PortalId, " Subscribers");
//Assign to user
oDnnRoleController.AddUserRole(this.PortalId, oUser.UserID, oCurrentRole.RoleID, Null.NullDate, Null.NullDate);
// oDnnRoleController.DeleteUserRole(this.PortalId, int.Parse(oUser.UserID.ToString()), oCurrentRole.RoleID);
}
The reason why same code works for one and not the other could be different password rules for these websites. Make sure you are generating a password that complies with the password requirements of the target website.

using C# to get an ec2-instance tag

I'm not a developer so maybe the answer is out there for a different solution but I can't really translate it from python or something else.
I'm trying to use the AWS .NET SDK to find an instance and then get the instance's tags. I've gotten as far as being able to determine if an instance is up and running or not. I also see how I can create and delete tags (not in code example below). But I don't see an easy way to actually check if a tag exists and get the value of the tag if it does exist.
Sorry if I'm missing the obvious but this is all new to me. Here's an example of the code I'm using to check if an instance is running.
instanceID = "i-myInstanceID";
do {
var myrequest = new DescribeInstanceStatusRequest();
DescribeInstanceStatusResponse myresponse = ec2.DescribeInstanceStatus(myrequest);
int isCount = myresponse.DescribeInstanceStatusResult.InstanceStatuses.Count;
for (int isc=0; isc < isCount; isc++) {
InstanceStatus instanceStatus = myresponse.DescribeInstanceStatusResult.InstanceStatuses[isc];
if (instanceStatus.InstanceId.Contains(instanceID)) {
Console.WriteLine("It looks like instance "+instanceID+" is running.");
idIdx = isc;
foundID = true;
break;
}
}
if ((foundID==false) && (secondCounter==1)) {
Console.Write("Looking for instance "+instanceID);
} else {
Console.Write(".");
}
Thread.Sleep(1000);
secondCounter++;
if (secondCounter > 5) {
break;
}
} while (foundID == false) ;
First send a DescribeInstancesRequest to get the list of Instances:
public DescribeInstancesResult GetInstances(Ec2Key ec2Key)
{
_logger.Debug("GetInstances Start.");
AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);
var ec2Request = new DescribeInstancesRequest();
DescribeInstancesResponse describeInstancesResponse = ec2.DescribeInstances(ec2Request);
DescribeInstancesResult result = describeInstancesResponse.DescribeInstancesResult;
_logger.Debug("GetInstances End.");
return result;
}
Then loop through the instances until you find the one you want, and then use the Tag.GetTagValueByKey method:
// This just calls the above code
DescribeInstancesResult ec2Instances = _ec2ResourceAccess.GetInstances(ec2Key);
var returnInstances = new List<Ec2UtilityInstance>();
foreach (var reservation in ec2Instances.Reservation)
{
foreach (var runningInstance in reservation.RunningInstance)
{
var returnInstance = new Ec2UtilityInstance();
returnInstance.InstanceId = runningInstance.InstanceId;
returnInstance.InstanceName = runningInstance.Tag.GetTagValueByKey("Name");
returnInstance.Status = (Ec2UtilityInstanceStatus)Enum.Parse(typeof(Ec2UtilityInstanceStatus), runningInstance.InstanceState.Name, true);
returnInstance.DefaultIp = runningInstance.Tag.GetTagValueByKey("DefaultIp");
returnInstance.InstanceType = runningInstance.InstanceType;
returnInstance.ImageId = runningInstance.ImageId;
returnInstances.Add(returnInstance);
}
}
Here is the link for full source that this was taken from:
https://github.com/escherrer/EC2Utilities
Common\Manager
and
Common\ResourceAccess

Categories

Resources