How to connect to WIFI AP using static ip address, not DHCP - android-wifi

I'm looking for how to connect to WIFI AP and found this.
How do I connect to a specific Wi-Fi network in Android programmatically?
And With the code above, I made up the below code.
public void connect_dhcp()
{
String sSSID = "TESTAP";
String sPassword = "12341234";
WifiConfiguration wfc = new WifiConfiguration();
wfc.SSID = "\"".concat(sSSID).concat("\"");
wfc.status = WifiConfiguration.Status.DISABLED;
wfc.priority = 40;
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wfc.preSharedKey = "\"".concat(sPassword).concat("\"");
WifiManager wfMgr = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
int networkId = wfMgr.addNetwork(wfc);
if (networkId != -1) {
Log.d("SCAN", "Success");
wfMgr.enableNetwork(networkId, true);
}
}
But I also need to connect with static ip.
Can anyone help me connect to WIFI AP with static ip?

Related

Prompts Login window in Crystal Report in ASP.NET

I am using VS 2012
MySql
mysql-connector-odbc-5.3.4-win32.msi
4.crystal report runtime on windows server 2008.
My web application works fine in my development system, but after deployment to Windows server 2008 , crystal reports ask for addition information about login information as given in following screen.
using the following code.
string databaseName = "hr";
string serverName = "192.168.137.6";
string userID = "co";
string pass = "password";
protected void btn_search_Click(object sender, EventArgs e)
{
CrystalReportViewer1.Visible = true;
ReportDocument reportDocument = new ReportDocument();
TableLogOnInfo TabLogOnInfo = new TableLogOnInfo();
TableLogOnInfos TabInfos = new TableLogOnInfos();
ConnectionInfo conInfo = new ConnectionInfo();
string reportPath = Server.MapPath(#"~/GeneralEmpReports/ddoWiseEmpRpt.rpt");
string ddoCode = tbx_ddoCode.Text.ToUpper();
reportDocument.Load(reportPath);
reportDocument.SetParameterValue("D", ddoCode);
conInfo.ServerName = serverName;
conInfo.DatabaseName = databaseName;
conInfo.UserID = userID;
conInfo.Password = pass;
conInfo.AllowCustomConnection = false;
conInfo.IntegratedSecurity = false;
foreach (CrystalDecisions.CrystalReports.Engine.Table T in reportDocument.Database.Tables)
{
TabLogOnInfo = T.LogOnInfo;
TabLogOnInfo.ConnectionInfo = conInfo;
T.ApplyLogOnInfo(TabLogOnInfo);
}
CrystalReportViewer1.ReportSource = reportDocument;
CrystalReportViewer1.ReuseParameterValuesOnRefresh = true;
CrystalReportViewer1.AutoDataBind = true;
CrystalReportViewer1.Zoom(80);
}
i don't know how to solve the issue.

Access web api 2 app from windows phone 8 application

I have a problem when I am trying to access my ASP.NET Web Api 2 application running on the localhost from windows phone 8 application. I have tried and looked for a lot examples how to do it but with no result. I tested my api using Fiddler and it works. I tested to access it from web application and it works but when I tried to access it from windows phone 8 app it doesn't. Can you tell me how to configure my windows phone 8 emulator to access it? Thank you in advance.
The emulator is a virtual machine so "localhost" inside your phone app means the emulator itself, not your host machine where you're running your web service. To access it, you have to provide the actual IP address of your host computer in the local network instead of "localhost". You can see what your IP is by running ipconfig in the cmd console.
here is a detail artical on accessing web api methods in Windows Phone 8
Calling Web API from a Windows Phone 8
to be specific here is how you get data from web API
string apiUrl = #"http://www.contoso.com/api/Books";
WebClient webClient = new WebClient();
webClient.Headers["Accept"] = "application/json";
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadCatalogCompleted);
webClient.DownloadStringAsync(new Uri(apiUrl));
private void webClient_DownloadCatalogCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
this.Items.Clear();
if (e.Result != null)
{
var books = JsonConvert.DeserializeObject<BookDetails[]>(e.Result);
int id = 0;
foreach (BookDetails book in books)
{
this.Items.Add(new ItemViewModel()
{
ID = (id++).ToString(),
LineOne = book.Title,
LineTwo = book.Author,
LineThree = book.Description.Replace("\n", " ")
});
}
this.IsDataLoaded = true;
}
}
catch (Exception ex)
{
this.Items.Add(new ItemViewModel()
{
ID = "0",
LineOne = "An Error Occurred",
LineTwo = String.Format("The following exception occured: {0}", ex.Message),
LineThree = String.Format("Additional inner exception information: {0}", ex.InnerException.Message)
});
}
}
Hope this helps

set mysql connection behind ssh in groovy script SoapUI

From groovy script in SoapUI I need to connect to a mysql database to perform some queries. The problem is that due to security reasons no external access is possible.
Therefore it is required to get an ssh access (like a tunnel) and invoke mysql locally.
Initially I was reading the below project properties and then connect to mysql:
ServerUrl=jdbc:mysql://10.255.255.122:3306/db
ServerDbUser=user
ServerDbPwd=password
ServerDriver=com.mysql.jdbc.Driver
def url=testRunner.testCase.testSuite.project.getPropertyValue("ServerUrl")
def usr=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbUser")
def pwd=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbPwd")
def driver=testRunner.testCase.testSuite.project.getPropertyValue("ServerDriver")
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver(driver)
sqlServer = Sql.newInstance(url, usr, pwd, driver)`
But this didn't work so now it is required to establish first a ssh connection to the server with the IP 10.255.255.122 and then open the mysql connection locally. So I guess the Server Url will change to:
ServerUrl=jdbc:mysql://127.0.0.1:3306/db
But I don't know how to set first the ssh connection to the server.
Can someone help me with this?
Thanks.
Have a look at http://forum.soapui.org/viewtopic.php?t=15400 and connect to remote mysql database through ssh using java
It will give you an idea about implementing it in soapUI.
Below is the code by Ripon Al Wasim which is available as an answer at the stackoverflow link mentioned above
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

How TransactionScope works with DTC and WCF?

I have WCF Service with following coding:
using (TransactionScope transScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
security = new Security(GetConnection(SecurityConstants.DatabaseName));
int userExists = security.UserRegistered(UserID,Pass);
transScope.Complete();
}
I have same method in DBA layer to run query by IExecuteResult as you can see here:
[Function(Name = SecurityConstants.SP_Name)]
public UserRegistered<IntegerOutput> IsUserExist(
[Parameter(Name = "USERID", DbType = "VarChar(15)")] string userID,
[Parameter(Name = "pass", DbType = "VarChar(25)")] string pass
)
{
IExecuteResult result = this.ExecuteMethodCall(this,((MethodInfo) (MethodInfo.GetCurrentMethod())), userID, pass);
return ((ISingleResult<IntegerOutput>)(result.ReturnValue));
}
Furthermore, I have checked MSDTC's configuration, but when I run my application it face to "Communication with the underlying transaction manager has failed" error. I have enabled DTC on my local machine and server side, but I still have problem. could you let me know is it for network setting or my local mochine or something else? could you please help me.

System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.