Android QR Code Scanner Not Recognizing Text or Wifi - qr-code

I am building an Android QR scanner app, and I used a code shared by "Android Coding Time" YouTube channel. The code is specified to read text, wifi and url.
The app ended up reading the URL but it's not recognizing text or Wifi. The code is attached, any thoughts?
// I even throw "Barcode.FORMAT_ALL_FORMATS" hoping it would work, but it didn't!
private void scanbarcode(ImageProxy image) {
#SuppressLint("UnsafeOptInUsageError") Image image1 = image.getImage();
assert image1 != null;
InputImage inputImage = InputImage.fromMediaImage(image1, image.getImageInfo().getRotationDegrees());
BarcodeScannerOptions options =
new BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_ALL_FORMATS,
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_AZTEC)
.build();
// the switch block
int valueType = barcode.getValueType();
switch (valueType) {
case Barcode.TYPE_WIFI:
String ssid = barcode.getWifi().getSsid();
String password = barcode.getWifi().getPassword();
int type = barcode.getWifi().getEncryptionType();
break;
case Barcode.TYPE_URL:
if (!bd.isAdded()) {
bd.show(fragmentManager, "");
}
bd.fetchurl(barcode.getUrl().getUrl());
String title = barcode.getUrl().getTitle();
String url = barcode.getUrl().getUrl();
break;
case Barcode.TYPE_TEXT:
byte[] codeText = barcode.getRawValue().getBytes(StandardCharsets.UTF_8);
break;

To share with you guys, I got the code running by changing the .setBarcodeFormats to:
new BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE)

Related

Serial Connection (Arduino --> Java)

this will be my first post and I will do my best to be clear and concise. I've checked some of the other posts on this forum but was unable to find a satisfactory answer.
My question pertains to the use of JavaFX and the jSSC(java simple serial connection) library. I've designed a very simple GUI application that will host four different charts. Two of the charts will display readings from temperature and solar sensors for the past hour, while the other two display that data over an extended period -- a 14-hour period. Eventually I would like to make that more flexible and set the application to "sleep" when the readings become roughly zero (night).
How can I stream data to display this data in real time?
After referencing several sources online and from "JavaFX 8 Intro. by Example", I've been able to construct most of the serial connection class. I'm having trouble processing the data readings, so that it can be displayed on the chart.
public class SerialComm implements SerialPortEventListener {
Date time = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("mm");
boolean connected;
StringBuilder sb;
private SerialPort serialPort;
final StringProperty line = new SimpleStringProperty("");
//Not sure this is necessary
private static final String [] PORT_NAMES = {
"/dev/tty.usbmodem1411", // Mac OS X
"COM11", // Windows
};
//Baud rate of communication transfer with serial device
public static final int DATA_RATE = 9600;
//Create a connection with the serial device
public boolean connect() {
String [] ports = SerialPortList.getPortNames();
//First, Find an instance of serial port as set in PORT_NAMES.
for (String port : ports) {
System.out.print("Ports: " + port);
serialPort = new SerialPort(port);
}
if (serialPort == null) {
System.out.println("Could not find device.");
return false;
}
//Operation to perform is port is found
try {
// open serial port
if(serialPort.openPort()) {
System.out.println("Connected");
// set port parameters
serialPort.setParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setEventsMask(SerialPort.MASK_RXCHAR);
serialPort.addEventListener(event -> {
if(event.isRXCHAR()) {
try {
sb.append(serialPort.readString(event.getEventValue()));
String str = sb.toString();
if(str.endsWith("\r\n")) {
line.set(Long.toString(time.getTime()).concat(":").concat(
str.substring(0, str.indexOf("\r\n"))));
System.out.println("line" + line);
sb = new StringBuilder();
}
} catch (SerialPortException ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex); }
}
});
}
} catch (Exception e) {
System.out.println("ErrOr");
e.printStackTrace();
System.err.println(e.toString());
}
return serialPort != null;
}
#Override
public void serialEvent(SerialPortEvent spe) {
throw new UnsupportedOperationException("Not supported yet.");
}
public StringProperty getLine() {
return line;
}
}
Within the try block, I understand the port parameters, but the eventListener is where I am having difficulty. The significance of the stringbuilder is to append data the new data as it is read from the device.
How will I account for the two sensor readings? Would I do that by creating separate data rates to differentiate between the incoming data from each sensor??
I hope that this is clear and that I've provided enough information but not too much. Thank you for any assistance.
-------------------------------UPDATE--------------------------
Since your reply Jose, I've started to make the additions to my code. Adding the listener within the JavaFX class, I'm running into some issues. I keep getting a NullPointerException, which I believe is the String[]data not being initialized by any data from the SerialCommunication class.
serialPort.addEventListener(event -> {
if(event.isRXCHAR()) {
try {
sb.append(serialPort.readString(event.getEventValue()));
String str = sb.toString();
if(str.endsWith("\r\n")) {
line.set(Long.toString(time.getTime()).concat(":").concat(
str.substring(0, str.indexOf("\r\n"))));
System.out.println("line" + line);
sb = new StringBuilder();
}
} catch (SerialPortException ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
} catch (Exception e) {
System.err.println(e.toString());
}
I'm adding the time to the data being read. As Jose mentioned below, I've added tags to the data variables within the arduino code, I'm using: Serial.print("Solar:"); Serial.println(solarData);
Rough code of the JavaFx listener:
serialPort.getLine().addListener((ov, t, t1) -> {
Platform.runLater(()-> {
String [] data = t1.split(":");
try {
//data[0] is the timestamp
//data[1] will contain the label printed by arduino "Solar: data"
switch (data[1]) {
case "Solar":
data[0].replace("Solar:" , "");
solarSeries.getData().add(new XYChart.Data(data[0], data[1]));
break;
case "Temperature":
temperatureSeries.getData().add(new XYChart.Data(data[0], data[1]));
break;
}
Is the reason this code has NullPointerException a result of the String [] data array being uninitialized?
Exception Error
Ports: /dev/tty.usbmodem1411Connected
Exception in thread "EventThread /dev/tty.usbmodem1411" java.lang.NullPointerException
at SerialComm.lambda$connect$0(SerialComm.java:61)
at SerialComm$$Lambda$1/1661773475.serialEvent(Unknown Source)
at jssc.SerialPort$LinuxEventThread.run(SerialPort.java:1299)
The SerialPortEventListener defined in the jssc library allows listening for serial port events. One of those events is the RXCHAR event, that occurs when the Arduino board is sending some data and some bytes are on the input buffer.
event.getEventValue() returns an int with the byte count, and serialPort.readString(event.getEventValue()) get the String format from those bytes.
Note that this method does not return a full line, so you need to listen to carriage return and line feed characters. Once you find "\r\n", you can get the line, and reset the StringBuilder for the next one:
sb.append(serialPort.readString(event.getEventValue()));
String str=sb.toString();
if(str.endsWith("\r\n")){
line.set(str.substring(0,str.indexOf("\r\n")));
sb=new StringBuilder();
}
where line is an observable String:
final StringProperty line=new SimpleStringProperty("");
On the Arduino side, if you want to send values from different sensors at different rates, I suggest you define on the Arduino sketch some identification string for each sensor, and you print for each value the id of its sensor.
For instance, these will be the readings you will get with the serial event listener:
ID1,val1
ID1,val2
ID2,val3
ID1,val4
ID3,val5
...
Finally, on the JavaFX thread, define a listener to changes in line and process the String to get the sensor and the value. Something like this:
serial.getLine().addListener(
(ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
Platform.runLater(()->{
String[] data=newValue.split("\\,");
if(data[0].equals("ID1"){
// add to chart from sensor 1, value data[1];
} else if(data[0].equals("ID2"){
// add to chart from sensor 2, value data[1];
} else if(data[0].equals("ID3"){
// add to chart from sensor 3, value data[1];
}
});
});
Note you need to add Platform.runLater(), since the thread that gets the data from serial port and updates line is not on the JavaFX thread.
From my experience, on the Arduino side, add a comma or something to separate the different values when you print and when you receive that string in Java simply split that string by commas.
String[] stringSeparate = str.split(",");

What is the necessary call to send data over COM port using OpenNETCF Port class?

I am trying to retrieve a value from a Zebra printer by interrogating it with this code:
public static string GetSettingFromPrinter(string cmd)
{
string setting = string.Empty;
try
{
BasicPortSettings bps = new BasicPortSettings();
bps.BaudRate = BaudRates.CBR_19200;
bps.Parity = OpenNETCF.IO.Serial.Parity.none;
bps.StopBits = OpenNETCF.IO.Serial.StopBits.one;
Port serialPort = new Port("COM1:", bps);
serialPort.Open();
byte[] sendBytes = Encoding.ASCII.GetBytes(cmd);
MessageBox.Show(Encoding.ASCII.GetString(sendBytes, 0, sendBytes.Length));
serialPort.Output = sendBytes;
serialPort.Query(); // <= this is new
byte[] responseBytes = serialPort.Input;
setting = GetString(responseBytes);
serialPort.Close();
return setting;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return setting;
}
}
However, I don't see where the Output is actually sent, or how to do that. My best guess was calling the Port.Query() method, but that doesn't work, either - at least there is nothing in setting / the Port.Input value after doing so.
I have successfully passed commands to the printer using the older SerialPort class:
public static bool SendCommandToPrinter(string cmd)
{
bool success; // init'd to false by default
try
{
SerialPort serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.Open();
serialPort.Write(cmd);
serialPort.Close();
success = true;
}
catch // may not need a try/catch block, as success defaults to false
{
success = false;
}
return success;
}
...but was advised not to use that due to its longness of tooth.
I would revert back to this snaggletooth if I knew how to read from the old SerialPort class. Does anybody know what I need to do to send sendBytes (and receive responseBytes)?
UPDATE
I tested "COM1" instead of "COM1:" (I used the latter because there is a post that says the colon is necessary (<= not medical advice, although that is doubtless true in that sense, too), but sans the ":" made no noticeable difference.
I then tried "string.Empty" in place of giving it a name, and got, "OpenNETCF.IO.Serial.CommPortException: CreateFileFailed 2 ..."
Onward...or is it Sideward...
FWIW, setting the Output property immediately sends the data on the wire. No additional call is necessary.

how can we store a html page into sqlite in blackberry on memory card / phone memory?

Below code specifies that we we can make http connection in blackberry and how to store html page as a string?
I am doing this but I am able to get that http request but when I get response i.e http_ok it is not correct so that I can save text oh html as a string and I can further store that into sqlite.
LabelField title = new LabelField("SQLite Create Database Sample",
LabelField.ELLIPSIS |
LabelField.USE_ALL_WIDTH);
setTitle(title);
add(new RichTextField("Creating a database."));
argURL="https://www.google.com:80";
try {
connDesc = connFact.getConnection(argURL);
if (connDesc != null) {
httpConn = (HttpConnection) connDesc.getConnection();
// //Send Data on this connection
// httpConn.setRequestMethod(HttpConnection.GET);
// //Server Response
StringBuffer strBuffer = new StringBuffer();
inStream = httpConn.openInputStream();
int chr;
int retResponseCode = httpConn.getResponseCode();
if (retResponseCode == HttpConnection.HTTP_OK) {
if (inStream != null) {
while ((chr = inStream.read()) != -1) {
strBuffer.append((char) chr);
}
serverResponceStr = strBuffer.toString();
// appLe.alertForms.get_userWaitAlertForm().append("\n"+serverResponceStr);
//returnCode = gprsConstants.retCodeSuccess;
}
} else {
//returnCode = gprsConstants.retCodeNOK;
}
}
} catch (Exception excp) {
//returnCode = gprsConstants.retCodeDisconn;
excp.printStackTrace();
} `enter code here`
The code does not perform any database functionality, however I tested and it does successfully perform an HttpRequest to an external URL. The data that comes back is based on the response of the server you are making the request to.
The code I used can be found here:
http://snipt.org/vrl7
The only modifications is to keep a running summary of various events, and the response is displayed in the RichTextField. Basically, this looks to be working as intended, and the resulting String should be able to be saved however you see fit; though you may need to be cautious of encoding when saving to a database so that special characters are not lost or misinterpreted.

Umbraco v4 vs Cute AJAX Uploader Control

I have a custom user control that i use in a page in Umbraco CMS... since upgrading to version 4, it seems this user control wont work any longer.
The user control contains an ajax uploader control (support request post here: http://cutesoft.net/forums/53732/ShowThread.aspx#53732), which allows users to upload images, then displays the uploaded images to the user. The control and image displays are contained within an UpdatePanel, which is where this problem is - seems the data getting sent back to the updatePanel is not valid, so the client is spitting the dummy and throwing this error:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '
<!DOCTYPE html PUBL'.
I think its somethihng to do with how Master Pages is implemented in Umbraco v4 that is causing this. Any ideas as to why this may have happened, and what i can look at to try to solve it?
FYI, here's a blog post that describes the error and its possible causes:
http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx
i'm doing any Response.write or Response.Redirect in the updatePanel
I'm not using any response filters
I've disabled server trace
I'm not using response.transfer
But, regardless of the above, this works fine using the same usercontrol on an Umbraco v3 site, which leads me to believe its somethign to do with v4 that's caused this.
Any suggestions greatly appreciated
I know that this whole answer is not directly a fix for your problem, but more like a workaround. this is because I am not familiar with the custom control you use.
i will however take a look tonight at your problem and see if i can find a solution for the code and plugin you use currently.
in the mean time i might give you some idea of the ajax upload i am using myself.
i know its a big chunk of code, but if you are interested you can go for it :)
my example case
I have an upload control in my own website and it works perfectly with umbraco.
the form and upload are powered with jQuery (upload is handled by jQuery.AjaxUpload plugin)
and i created a generic handler inside my umbraco folder which handles the file on the server.
creating a media item in the media library for it (and in my case beeing an avatar uploader on your profile page, it also adds the newly created mediaitem to the member's avatar property)
jQuery code: (stored in script block in the head of your page, or in a separate script)
initializeChangeAvatarForm = function() {
var button = $('#submitChangeAvatar'), interval;
new AjaxUpload(button,{
action: '/umbraco/AjaxFileUpload.ashx',
name: 'myfile',
onSubmit : function(file, ext){
// change button text to uploading + add class (with animating background loading image)
button.text('Uploading').addClass('loading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
},
onComplete: function(file, response){
button.text('Upload nieuw').removeClass('loading');
// Although plugins emulates hover effect automatically,
// it doens't work when button is disabled
button.removeClass('hover');
window.clearInterval(interval);
// enable upload button
this.enable();
}
});
};
$(document).ready(function(){
initializeChangeMailForm();
});
html code in your body:
<div id="container"><h2>Upload Avatar</h2><button class="button" id="submitChangeAvatar" type="button">Upload new</button></div>
jQuery ajaxupload plugin: (/scripts/jQuery.ajaxupload.js)
'since this code is too long i added a link directly to the .js file i use
'and another link to the page where i got the plugin
handler .ashx: (stored inside /umbraco/AjaxFileUpload.ashx)
using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Xml;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.member;
namespace SH.umbServices
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AjaxFileUpload : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string strResponse = "error";
try
{
//string strFileName = Path.GetFileName(context.Request.Files[0].FileName);
//string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
//string strSaveLocation = context.Server.MapPath("../images/temp") + "\\" + strFileName;
//context.Request.Files[0].SaveAs(strSaveLocation);
UmbracoSave(context);
strResponse = "success";
}
catch
{
}
context.Response.ContentType = "text/plain";
context.Response.Write(strResponse);
}
public bool IsReusable
{
get
{
return false;
}
}
#region "umbMediaItem"
protected string UmbracoSave(HttpContext context)
{
string mediaPath = "";
if (context.Request.Files[0] != null)
{
if (context.Request.Files[0].FileName != "")
{
// Find filename
string _text = context.Request.Files[0].FileName;
string _ext = Path.GetExtension(context.Request.Files[0].FileName);
string filename;
string _fullFilePath;
//filename = _text.Substring(_text.LastIndexOf("\\") + 1, _text.Length - _text.LastIndexOf("\\") - 1).ToLower();
filename = Path.GetFileName(_text);
string _filenameWithoutExtention = filename.Replace(_ext, "");
int _p = 1212; // parent node.. -1 for media root)
// create the Media Node
umbraco.cms.businesslogic.media.Media m = umbraco.cms.businesslogic.media.Media.MakeNew(
_filenameWithoutExtention, umbraco.cms.businesslogic.media.MediaType.GetByAlias("image"), User.GetUser(0), _p);
// Create a new folder in the /media folder with the name /media/propertyid
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString()));
_fullFilePath = System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.Path + "/../media/" + m.Id.ToString() + "/" + filename);
context.Request.Files[0].SaveAs(_fullFilePath);
// Save extension
//string orgExt = ((string)_text.Substring(_text.LastIndexOf(".") + 1, _text.Length - _text.LastIndexOf(".") - 1));
string orgExt = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
orgExt = orgExt.Trim(char.Parse("."));
try
{
m.getProperty("umbracoExtension").Value = orgExt;
}
catch { }
// Save file size
try
{
System.IO.FileInfo fi = new FileInfo(_fullFilePath);
m.getProperty("umbracoBytes").Value = fi.Length.ToString();
}
catch { }
// Check if image and then get sizes, make thumb and update database
if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt + ",") > 0)
{
int fileWidth;
int fileHeight;
FileStream fs = new FileStream(_fullFilePath,
FileMode.Open, FileAccess.Read, FileShare.Read);
System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
fileWidth = image.Width;
fileHeight = image.Height;
fs.Close();
try
{
m.getProperty("umbracoWidth").Value = fileWidth.ToString();
m.getProperty("umbracoHeight").Value = fileHeight.ToString();
}
catch { }
// Generate thumbnails
string fileNameThumb = _fullFilePath.Replace("." + orgExt, "_thumb");
generateThumbnail(image, 100, fileWidth, fileHeight, _fullFilePath, orgExt, fileNameThumb + ".jpg");
image.Dispose();
}
mediaPath = "/media/" + m.Id.ToString() + "/" + filename;
m.getProperty("umbracoFile").Value = mediaPath;
m.XmlGenerate(new XmlDocument());
Member mbr = Member.GetCurrentMember();
umbraco.cms.businesslogic.property.Property avt = mbr.getProperty("memberAvatar");
avt.Value = m.Id;
mbr.XmlGenerate(new XmlDocument());
mbr.Save();
//string commerceFileName = mediaPath;
//CommerceSave(commerceFileName);
}
}
return mediaPath;
}
protected void generateThumbnail(System.Drawing.Image image, int maxWidthHeight, int fileWidth, int fileHeight, string fullFilePath, string ext, string thumbnailFileName)
{
// Generate thumbnail
float fx = (float)fileWidth / (float)maxWidthHeight;
float fy = (float)fileHeight / (float)maxWidthHeight;
// must fit in thumbnail size
float f = Math.Max(fx, fy); //if (f < 1) f = 1;
int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);
// fixes for empty width or height
if (widthTh == 0)
widthTh = 1;
if (heightTh == 0)
heightTh = 1;
// Create new image with best quality settings
Bitmap bp = new Bitmap(widthTh, heightTh);
Graphics g = Graphics.FromImage(bp);
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// Copy the old image to the new and resized
Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
// Copy metadata
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo codec = null;
for (int i = 0; i < codecs.Length; i++)
{
if (codecs[i].MimeType.Equals("image/jpeg"))
codec = codecs[i];
}
// Set compresion ratio to 90%
EncoderParameters ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
// Save the new image
bp.Save(thumbnailFileName, codec, ep);
bp.Dispose();
g.Dispose();
}
#endregion
}
}
I hope this shed some light on what i use.
Pfew,..That's a lot of code.
I was only interessted in saving media in Umbraco but it's nice to see a jQuery upload too.
What upload jQuery lib your using? I've found serveral.
You could make the code a bit simpler by using Path.Combine, FileInfo.Extension merging if's and a few extra variables here an there. But hey I've got Resharper to make my live easier.

How do I get an already (basic) authenticated context to call a web service behind the same authentication?

I have a site behind basic authentication (IIS6).
Part of this site calls a web service that is also part of the site and thus behind basic authentication as well.
However, when this happens the calling code receives a 401 Authentication Error.
I've tried a couple of things, with the general recommendation being code like this:
Service.ServiceName s = new Service.ServiceName();
s.PreAuthenticate = true;
s.Credentials = System.Net.CredentialCache.DefaultCredentials;
s.Method("Test");
However, this does not seem to resolve my problem.
Any advice?
Edit
This seems to be a not uncommon issue but so far I have found no solutions.
Here is one thread on the topic.
Solution: (I am almost certain this will help someone)
See this link for the source of this solution in VB (thanks jshardy!), all I did was convert to C#.
NB: You must be using ONLY basic authentication on IIS for this to work, but it can probably be adapted. You also need to pass a Page instance in, or at least the Request.ServerVariables property (or use 'this' if called from a Page code-behind directly). I'd tidy this up and probably remove the use of references but this is a faithful translation of the original solution and you can make any amendments necessary.
public static void ServiceCall(Page p)
{
LocalServices.ServiceName s = new LocalServices.ServiceName();
s.PreAuthenticate = true; /* Not sure if required */
string username = "";
string password = "";
string domain = "";
GetBasicCredentials(p, ref username, ref password, ref domain);
s.Credentials = new NetworkCredential(username, password, domain);
s.ServiceMethod();
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void GetBasicCredentials(Page p, ref string rstrUser, ref string rstrPassword, ref string rstrDomain)
{
if (p == null)
{
return;
}
rstrUser = "";
rstrPassword = "";
rstrDomain = "";
rstrUser = p.Request.ServerVariables["AUTH_USER"];
rstrPassword = p.Request.ServerVariables["AUTH_PASSWORD"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
/* MSDN KB article 835388
BUG: The Request.ServerVariables("AUTH_PASSWORD") object does not display certain characters from an ASPX page */
string lstrHeader = p.Request.ServerVariables["HTTP_AUTHORIZATION"];
if (!string.IsNullOrEmpty(lstrHeader) && lstrHeader.StartsWith("Basic"))
{
string lstrTicket = lstrHeader.Substring(6);
lstrTicket = System.Text.Encoding.Default.GetString(Convert.FromBase64String(lstrTicket));
rstrPassword = lstrTicket.Substring((lstrTicket.IndexOf(":") + 1));
}
/* At least on my XP Pro machine AUTH_USER is not set (probably because we're using Forms authentication
But if the password is set (either by AUTH_PASSWORD or HTTP_AUTHORIZATION)
then we can use LOGON_USER*/
if (string.IsNullOrEmpty(rstrUser) && !string.IsNullOrEmpty(rstrPassword))
{
rstrUser = p.Request.ServerVariables["LOGON_USER"];
SplitDomainUserName(rstrUser, ref rstrDomain, ref rstrUser);
}
}
/* Converted from: http://forums.asp.net/t/1172902.aspx */
private static void SplitDomainUserName(string pstrDomainUserName, ref string rstrDomainName, ref string rstrUserName)
{
rstrDomainName = "";
rstrUserName = pstrDomainUserName;
int lnSlashPos = pstrDomainUserName.IndexOf("\\");
if (lnSlashPos > 0)
{
rstrDomainName = pstrDomainUserName.Substring(0, lnSlashPos);
rstrUserName = pstrDomainUserName.Substring(lnSlashPos + 1);
}
}
The Line:
s.Credentials = System.Net.CredentialCache.DefaultCredentials();
Maybe you should try :
s.Credentials = HttpContext.Current.User.Identity;

Resources