Connection to data server fails in IIS - c#

I have developed a website asp.net-mvc-4in Visual Studio-2010 which gets data from another sql data server that is placed on another location. I used port 443 to make connection and user login to get data. Website works fine in debug mode and it extracts data from the data server but when I upload the website over windows IIS it does not make any connection with the data server and hence doest not get data. It fails at the point
if (c.TryLogOn(AccountData.LogInUserName, AccountData.PW))
complete method is
try {
using (Client c = AccountData.c)
//using (TcpClient c = new TcpClient())
{
if (c.TryLogOn(AccountData.LogInUserName, AccountData.PW))
{
imc.Search.Base.Query.Query q = new imc.Search.Base.Query.Query();
AddAttributeListForFahrzeug(q);
AttributeValuesCollection values = c.FindInstances(q);
if (tempVehicleType == "all")
{
foreach (object[] av in values)
{
Fahrzeug d = NewFahrzeug(av);
d.VehicleType = tempVehicleType;
returnValue.Add(d);
}
}
else
{
foreach (object[] av in values)
{
Fahrzeug d = NewFahrzeug(av);
if (d.FzgBeschreibung == tempVehicleType)
{
d.VehicleType = tempVehicleType;
returnValue.Add(d);
}
//d.VehicleType = tempVehicleType;
}
}
c.LogOff();
}
}
} catch ( Exception ){
}
Connection to the client
static public AccountSettings GetAccountData()
{
AccountSettings AccountData = new AccountSettings();
System.Security.SecureString Pw = new System.Security.SecureString();
string PwWord = "**********";
string LogInUserName = "username";
foreach (char ch in PwWord)
{
Pw.AppendChar(ch);
}
//AccountData.c = new Client("abc.xyz.zhg.com", 443, true, ConnectionMode.Internet);
AccountData.c = new Client("abc.xyz.zhg.com", 1199, false, ConnectionMode.Remote);
AccountData.PW = Pw;
AccountData.LogInUserName = LogInUserName;
return (AccountData);
}
Then
AccountSettings AccountData = GetAccountData();

Related

How do I get a C# connection to MySQL on AWS

I'm trying to open a connection to a MySql database which is on AWS behind SSH but having major issues.
static void Main(string[] args)
{
try
{
var sshServer = "11.111.11.11";
var sshUserName = "shane";
var sshPassword = "";
var databaseServer = #"hello202006662000000666.abcdefghijk.ap - southeast - 2.rds.amazonaws.com";
var databaseUserName = "shane";
var databasePassword = "password";
var SSHPrivateKeyFile = #"C:\Users\sshane\myprivatekey.ppk";
var SSHPassPhrase = "sdkypfihsblkdcbsadl;kvgsiudgf";
var databasename = "production";
var (sshClient, localPort) = ConnectSsh(sshServer, sshUserName, sshPassword, SSHPrivateKeyFile, SSHPassPhrase, 22, databaseServer, 3306);
using (sshClient)
{
Console.WriteLine(sshClient);
Console.WriteLine(localPort);
MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder
{
Server = "localhost",
Port = localPort,
Database = "production",
UserID = "shane",
Password = "Jopassword"
};
using (var connection = new MySqlConnection(csb.ConnectionString))
{
Console.WriteLine(connection.Ping());
connection.Open();
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static (SshClient SshClient, uint Port) ConnectSsh(string sshHostName, string sshUserName, string sshPassword = null,
string sshKeyFile = null, string sshPassPhrase = null, int sshPort = 22, string databaseServer = "localhost", int databasePort = 3306)
{
// check arguments
if (string.IsNullOrEmpty(sshHostName))
throw new ArgumentException($"{nameof(sshHostName)} must be specified.", nameof(sshHostName));
if (string.IsNullOrEmpty(sshHostName))
throw new ArgumentException($"{nameof(sshUserName)} must be specified.", nameof(sshUserName));
if (string.IsNullOrEmpty(sshPassword) && string.IsNullOrEmpty(sshKeyFile))
throw new ArgumentException($"One of {nameof(sshPassword)} and {nameof(sshKeyFile)} must be specified.");
if (string.IsNullOrEmpty(databaseServer))
throw new ArgumentException($"{nameof(databaseServer)} must be specified.", nameof(databaseServer));
// define the authentication methods to use (in order)
var authenticationMethods = new List<AuthenticationMethod>();
if (!string.IsNullOrEmpty(sshKeyFile))
{
authenticationMethods.Add(new PrivateKeyAuthenticationMethod(sshUserName,
new PrivateKeyFile(sshKeyFile, string.IsNullOrEmpty(sshPassPhrase) ? null : sshPassPhrase)));
}
// connect to the SSH server
var sshClient = new SshClient(new ConnectionInfo(sshHostName, sshPort, sshUserName, authenticationMethods.ToArray()));
sshClient.Connect();
// forward a local port to the database server and port, using the SSH server
var forwardedPort = new ForwardedPortLocal("127.0.0.1", databaseServer, (uint)databasePort);
sshClient.AddForwardedPort(forwardedPort);
forwardedPort.Start();
return (sshClient, forwardedPort.BoundPort);
}
The error I'm getting is 'reading from the stream has failed'.
The SSH seems to be OK, but I can't establish a connection to the MySql db. Have been trying for a couple of days now, and I'm at a loss. Any help would be appreciated.

C# Api Web Client Sends Duplicate data instead of only 1Data

So i made a Windows Service API to Php from biometrics .everytime i send data via Web Client it sends Duplicate data instead of only sending 1 data ex:
Web Service -> Sends -> 1.Cardo Dalisay 01/01/2018 1:01:10PM -> 1.Cardo Dalisay 01/01/2018 1:01:10PM
//Get Data from biometric
ICollection<MachineInfo> lstmachineInfo = manipulator.GetLogData(objZkeeper, int.Parse(MachineNo));
//if its not null
if (lstmachineInfo != null && lstmachineInfo.Count > 0)
{
//new list for new updated data
List<MachineInfo.Datasend>zkteco = new List<MachineInfo.Datasend>();
const string encryptionkey = #"ZREpfb7s2q0+Jq598jTlGTSHovHMJ1ok";
//lambda which fetch only new data
var result = lstmachineInfo.ToList().Where(a => a.datetime >= DateTime.Now.AddMinutes(-1)).ToList();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//webclient is here
using (var webclient = new WebClient())
{
//fetch the newly data
foreach (var data in result)
{
//store then to new list
zkteco.Add(new MachineInfo.Datasend
{
_machineNumber = data.MachineNumber,
_subscription = Subscription,
_branchid = BranchID,
_userid = data.UserID,
_DateTimeRecord = data.DateTimeRecord,
_Checktype = data.InOut,
_Accesstoken = AccessToken
});
string JsonResponse = JsonConvert.SerializeObject(zkteco);
}
//fetch the newly stored data
foreach (var zktecolist in zkteco)
{
//namevaluecollection for webclient
var values = new NameValueCollection();
values["machineid"] = zktecolist._machineNumber.ToString();
values["subscription"] = zktecolist._subscription.ToString();
values["branchid"] = zktecolist._branchid.ToString();
values["userid"] = zktecolist._userid.ToString();
values["datetime"] = zktecolist._DateTimeRecord;
values["checktype"] = zktecolist._Checktype.ToString();
values["accesstoken"] = zktecolist._Accesstoken.ToString();
//Request follows
//below is the webclient request
var request = webclient.UploadValues("http://192.168.1.119/api/biometric_activity?data", values);
var response = Encoding.UTF8.GetString(request);
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(response);
if (apiResponse.status == "Ok")
{
WriteToFile("test" + apiResponse.description + " -> " + apiResponse.message + "status -> " + apiResponse.status);
}
else if (apiResponse.status != "Ok")
{
WriteToFile("No Data has been fetch");
}
}
}
}
else
{
objZkeeper = new ZkemClient(RaiseDeviceEvent);
isDeviceConnected = objZkeeper.Connect_Net(IPAddress, Port);
WriteToFile("failed in connecting with device, reconnecting ....");
}
}

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. when access local database

I have no idea.. why this occurs.
In debug mode it is running well .
however, now I am trying to run my project in IIS web server and
it doesn't runs well.
I can access the main page of my project. but when I try to access the local database, the following error shows up.
this is my log file and codes:
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine("아님여기?"+ex.Message);
file2.Close(); //디버깅 계속................
}
In this catch I have the following error:
provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server
I am sorry that I can not explain which line is generating this exception because there's no exception occurring in debug mode...
Here is the code for Page Load:
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Form.Enctype = "multipart/form-data";
WA = Request.QueryString["WA"];
if (string.IsNullOrEmpty(WA)) WA = "off";
string qstr = null;
qstr = Request.QueryString["vCnt"]; //ㅇㅈ이파라메터 들은 어디서...??
if (qstr != null && qstr != "") vCnt = Int32.Parse(qstr);
if (!IsPostBack)
{
Keywords = Request.QueryString["keywords"]; //ㅇㅈ search main -> searh 버튼 클릭
VideoSearch = Request.QueryString["VideoSearch"];//ㅇㅈ ~^~^~
// 스마트폰에서 포스팅 되었을 때
if (Request.UserAgent.Contains("Android"))
{
if (Request.Cookies["VIDEOSEARCH"] != null && Request.Cookies["VIDEOSEARCH"].Value != "")
{
VideoSearch = Request.Cookies["VIDEOSEARCH"].Value;
MAM.Models.Utils.CookieManager("VIDEOSEARCH", "");
}
}
if (!String.IsNullOrEmpty(Keywords) && !Keywords.Contains("null")) SearchTextbox2.Text = Keywords;
Debug.WriteLine("search text is " + SearchTextbox2.Text);
Debug.Flush();
try
{
if (!string.IsNullOrEmpty(VideoSearch))
{
//ㅇㅈ DNA를 추출하여 유사 동영상을 돌려받음.
string results = RetrieveDNAfromVideo(System.Web.HttpUtility.UrlDecode(VideoSearch)/*video name*/);
string[] lines = results.Split(new string[] { "\r\n" }, StringSplitOptions.None);
vSearchResults = new List<VSearchResult>();
foreach (string line in lines)
{
string[] words = line.Split(',');
VSearchResult vSearchResult = new VSearchResult();
vSearchResult.VideoID = Int32.Parse(words[0]);
vSearchResult.idx = Int32.Parse(words[1]);
vSearchResult.RGBdifferce = Int32.Parse(words[2]);
vSearchResults.Add(vSearchResult);
} //ㅇㅈ vSearchResults : RetrieveDNAfromVideo가 알려준유사동영상정보
MAMDataContext db = new MAMDataContext();
List<int> VideoIDs = (List<int>)vSearchResults.Select(v => v.VideoID).ToList();
//vdo = (List<Video>)(from a in db.Video
// join b in vSearchResults
// on a.id equals b.VideoID
// orderby b.RGBdifferce
// select a).ToList();
vdo = (List<Video>)(from a in db.Videos
where VideoIDs.Contains(a.id)
select a).ToList(); //ㅇㅈ vdo는 결국, RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들
vSearchResults2 = new List<VSearchResult2>();
VSearchResult v1 = null;
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v1 = vSearchResults.Where(t => t.VideoID == v.id).OrderBy(t => t.RGBdifferce).FirstOrDefault();//ㅇㅈ ㅇㄱㅁㅇ
// ㅇㅈ RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들[-> RGBdifferce가 가장작은 애] [] 무슨의미??
v2.idx = v1.idx;
v2.RGBdifferce = v1.RGBdifferce;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Serach done");
Debug.Flush();
}
if (!string.IsNullOrEmpty(Keywords))
{
string ret2 = null;
string str1 = null;
if (string.IsNullOrEmpty(Keywords))
{
Keywords = SearchTextbox2.Text;
}
if (string.IsNullOrEmpty(str1)) str1 = Keywords; //ㅇㅈ str1 은 질의의도??
string[] searchTextArray = str1.Split(' ');
int cnt1 = searchTextArray.Count();
string st1 = ""; string st2 = ""; string st3 = "";
if (cnt1 > 0) st1 = searchTextArray[0];
if (cnt1 > 1) st2 = searchTextArray[1];
if (cnt1 > 2) st3 = searchTextArray[2];
MAMDataContext db = new MAMDataContext();
vdo = (List<Video>)db.Videos.Where(v => v.overview.Contains(st1)
|| (cnt1 > 1 ? v.overview.Contains(st2) : false)
|| (cnt1 > 2 ? v.overview.Contains(st3) : false)).ToList();//ㅇㅈ 검색어를 overview에 가지고 있는 동영상 리스트
vSearchResults2 = new List<VSearchResult2>();
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v2.idx = 0;
v2.RGBdifferce = 0;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Search");
}
}
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine(ex.Message);
file2.Close(); //디버깅 계속................
}
Debug.WriteLine("Search End");
}
if (fUpload.PostedFile != null) //ㅇㅈ
{
fileupload1();
}
else
{
}
}
this is a guess because you did not provide a key information: the connection string.
my guess is that the application is using integrated authentication hence while debugging the access to the database is done using your credentials: as the developer you are likely allowed to do almost everything on the db so the application works correctly.
when the application is deployed the login to the database is performed using the credentials of the application pool used to run the application itself.
as a test you can change the user of the application pool on the iis server to use an account enabled on the db and retry to login.
there are two solutions:
- configure the application pool to use a specific windows user that is allowed to interact with the db
- change the connection string to log onto the db as a sql user (allowed to interact with the db)

Programatically create an IIS website on button click [duplicate]

We have been able to create a web site. We did this using the information in this link:
https://msdn.microsoft.com/en-us/library/ms525598.aspx
However, we would like to use a port number other that port 80. How do we do this?
We are using IIS 6
If you're using IIS 7, there is a new managed API called Microsoft.Web.Administration
An example from the above blog post:
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.CommitChanges();
If you're using IIS 6 and want to do this, it's more complex unfortunately.
You will have to create a web service on every server, a web service that handles the creation of a website because direct user impersonation over the network won't work properly (If I recall this correctly).
You will have to use Interop Services and do something similar to this (This example uses two objects, server and site, which are instances of custom classes that store a server's and site's configuration):
string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
DirectoryEntry w3svc = new DirectoryEntry(metabasePath, server.Username, server.Password);
string serverBindings = ":80:" + site.HostName;
string homeDirectory = server.WWWRootPath + "\\" + site.FolderName;
object[] newSite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };
object websiteId = (object)w3svc.Invoke("CreateNewSite", newSite);
// Returns the Website ID from the Metabase
int id = (int)websiteId;
See more here
Heres the solution.
Blog article : How to add new website in IIS 7
On Button click :
try
{
ServerManager serverMgr = new ServerManager();
string strWebsitename = txtwebsitename.Text; // abc
string strApplicationPool = "DefaultAppPool"; // set your deafultpool :4.0 in IIS
string strhostname = txthostname.Text; //abc.com
string stripaddress = txtipaddress.Text;// ip address
string bindinginfo = stripaddress + ":80:" + strhostname;
//check if website name already exists in IIS
Boolean bWebsite = IsWebsiteExists(strWebsitename);
if (!bWebsite)
{
Site mySite = serverMgr.Sites.Add(strWebsitename.ToString(), "http", bindinginfo, "C:\\inetpub\\wwwroot\\yourWebsite");
mySite.ApplicationDefaults.ApplicationPoolName = strApplicationPool;
mySite.TraceFailedRequestsLogging.Enabled = true;
mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
serverMgr.CommitChanges();
lblmsg.Text = "New website " + strWebsitename + " added sucessfully";
}
else
{
lblmsg.Text = "Name should be unique, " + strWebsitename + " is already exists. ";
}
}
catch (Exception ae)
{
Response.Redirect(ae.Message);
}
Looping over sites whether name already exists
public bool IsWebsiteExists(string strWebsitename)
{
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
foreach (Site site in sitecollection)
{
if (site.Name == strWebsitename.ToString())
{
flagset = true;
break;
}
else
{
flagset = false;
}
}
return flagset;
}
Try the following Code to Know the unUsed PortNo
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
// Find unused ID PortNo for new web site
bool found_valid_port_no = false;
int random_port_no = 1;
do
{
bool regenerate_port_no = false;
System.Random random_generator = new Random();
random_port_no = random_generator.Next(9000,15000);
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
int site_id = Convert.ToInt32(e.Name);
//For each detected ID find the port Number
DirectoryEntry vRoot = new DirectoryEntry("IIS://localhost/W3SVC/" + site_id);
PropertyValueCollection pvcServerBindings = vRoot.Properties["serverbindings"];
String bindings = pvcServerBindings.Value.ToString().Replace(":", "");
int port_no = Convert.ToInt32(bindings);
if (port_no == random_port_no)
{
regenerate_port_no = true;
break;
}
}
}
found_valid_port_no = !regenerate_port_no;
} while (!found_valid_port_no);
int newportId = random_port_no;
I have gone though all answer here and also tested. Here is the most clean smarter version of answer for this question. However this still cant work on IIS 6.0. so IIS 8.0 or above is required.
string domainName = "";
string appPoolName = "";
string webFiles = "C:\\Users\\John\\Desktop\\New Folder";
if (IsWebsiteExists(domainName) == false)
{
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add(domainName, "http", "*:8080:", webFiles);
iisManager.ApplicationDefaults.ApplicationPoolName = appPoolName;
iisManager.CommitChanges();
}
else
{
Console.WriteLine("Name Exists already");
}
public static bool IsWebsiteExists(string strWebsitename)
{
ServerManager serverMgr = new ServerManager();
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
flagset = sitecollection.Any(x => x.Name == strWebsitename);
return flagset;
}
This simplified method will create a site with default binding settings, and also create the application pool if needed:
public void addIISApplication(string siteName, string physicalPath, int port, string appPoolName)
{
using (var serverMgr = new ServerManager())
{
var sitecollection = serverMgr.Sites;
if (!sitecollection.Any(x => x.Name.ToLower() == siteName.ToLower()))
{
var appPools = serverMgr.ApplicationPools;
if (!appPools.Any(x => x.Name.ToLower() == appPoolName.ToLower()))
{
serverMgr.ApplicationPools.Add(appPoolName);
}
var mySite = serverMgr.Sites.Add(siteName, physicalPath, port);
mySite.ApplicationDefaults.ApplicationPoolName = appPoolName;
serverMgr.CommitChanges();
}
}
}
In properties of site select "Web Site" tab and specify TCP Port.
In studio to debug purpose specify http://localhost:<port>/<site> at tab Web for "Use Local IIS Web Server"

How do I implement a C# Thrift service and consume it with a Silverlight client?

I'm current looking at Thrift to use as a RPC framework for our apps (mostly written in C# and Silverlight). I've come as far as implementing a service and consuming it from a C# console app (using a socket as transport).
For the C# server side code my code looked like: (basically copying the tutorials included with the source code)
MyServiceHandler handler = new MyServiceHandler();
MyService.Processor processor = new MyService.Processor(handler);
TServerTransport serverTransport = new TServerSocket(9090);
TServer server = new TSimpleServer(processor, serverTransport);
server.Serve();
For the client side code it looked like:
TTransport transport = new TSocket("localhost", 9090);
TProtocol protocol = new TBinaryProtocol(transport);
MyService.Client client = new MyService.Client(protocol);
transport.Open();
client.SomeServiceCall();
However, we will be consuming the service from a Silverlight client, and unfortunately there is no support for sockets in Silverlight for Thrift. I assume I'm forced to use HTTP communication between the client and service, using Thrift's C# THttpClient and THttpHandler classes? I could not find any examples of how to do this out there, can anyone point me in the right direction? Some example server and client side code would be appreciated.
It seems that this issue was already addressed by this guy. According to this JIRA, the fix is available in Thrift 0.9. You can either try this snapshot (note that, as it's not a final release, it might not be stable) or you can apply this patch to the 0.8 release.
I believe by now you would have understood, there is no direct way of communicating from Silverlight to the Cassandra database either using Thrift or any other clients.
I have one simple option related to this. Write a Silverlight enabled web service and consume it from the client.
For example, on the server side you can have a web service which does insert/update/read etc., like this. I just managed to pull out some code which we use for our project. Hope this helps.
using Apache.Cassandra;
using Thrift.Protocol;
using Thrift.Transport;
namespace CassandraWebLibrary
{
public class MyDb
{
String _host;
int _port;
String _keyspace;
bool _isConnected;
TTransport _transport = null;
Apache.Cassandra.Cassandra.Client _client = null;
String columnFamily = "ColumnFamilyName";
public VazhikaattiDB(String host, int port, String keyspace)
{
_host = host;
_port = port;
_keyspace = keyspace;
_isConnected = false;
}
public bool Connect()
{
try
{
_transport = new TFramedTransport(new TSocket(_host, _port));
TProtocol protocol = new TBinaryProtocol(_transport);
_client = new Apache.Cassandra.Cassandra.Client(protocol);
_transport.Open();
_client.set_keyspace(_keyspace);
_isConnected = true;
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
return _isConnected;
}
public bool Close()
{
if (_transport.IsOpen)
_transport.Close();
_isConnected = false;
return true;
}
public bool InsertData(Send your data as parameters here)
{
try
{
List<Column> list = new List<Column>();
string strKey = keyvalue;
#region Inserting into Coulmn family
List<Byte> valbytes = new List<byte>(BitConverter.GetBytes(value)); //You might have to pad this with more bytes to make it length of 8 bytes
Column doublecolumn1 = new Column()
{
Name = Encoding.UTF8.GetBytes("column1"),
Timestamp = timestampvalue,
Value = valbytes.ToArray()
};
list.Add(doublecolumn1);
Column stringcolumn2 = new Column()
{
Name = Encoding.UTF8.GetBytes("column2"),
Timestamp = timestampvalue,
Value = Encoding.UTF8.GetBytes("StringValue")
};
list.Add(stringcolumn2);
Column timecolumn3 = new Column()
{
Name = Encoding.UTF8.GetBytes("column3"),
Timestamp = timestampvalue,
Value = BitConverter.GetBytes(DateTime.Now.Ticks)
};
list.Add(timecolumn3);
#endregion
ColumnParent columnParent = new ColumnParent();
columnParent.Column_family = columnFamily;
Byte[] key = Encoding.UTF8.GetBytes(strKey);
foreach (Column column in list)
{
try
{
_client.insert(key, columnParent, column, ConsistencyLevel.QUORUM);
}
catch (Exception e)
{
log.Error(e.ToString());
}
}
return true;
}
catch (Exception ex)
{
log.Error(ex.ToString());
return false;
}
}
public List<YourReturnObject> GetData(parameters)
{
try
{
ColumnParent columnParent = new ColumnParent();
columnParent.Column_family = columnFamily;
DateTime curdate = startdate;
IndexExpression indExprsecondkey = new IndexExpression();
indExprsecondkey.Column_name = Encoding.UTF8.GetBytes("column");
indExprsecondkey.Op = IndexOperator.EQ;
List<Byte> valbytes = PadLeftBytes((int)yourid, 8);
indExprsecondkey.Value = valbytes.ToArray();
indExprList.Add(indExprsecondkey);
IndexClause indClause = new IndexClause()
{
Expressions = indExprList,
Count = 1000,
Start_key = Encoding.UTF8.GetBytes("")
};
SlicePredicate slice = new SlicePredicate()
{
Slice_range = new SliceRange()
{
//Start and Finish cannot be null
Start = new byte[0],
Finish = new byte[0],
Count = 1000,
Reversed = false
}
};
List<KeySlice> keyslices = _client.get_indexed_slices(columnParent, indClause, slice, ConsistencyLevel.ONE);
foreach (KeySlice ks in keyslices)
{
String stringcolumnvalue = Encoding.UTF8.GetString(cl.Column.Value);
double doublevalue= (Double)BitConverter.ToDouble(cl.Column.Value);
long timeticks = BitConverter.ToInt64(cl.Column.Value, 0);
DateTime dtcolumntime = new DateTime(timeticks);
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
return yourdatalist;
}
}
}
Now the above class can be used by your webservice, which in turn will be used by Silverlight. Btw, you'll have to take care of other silverlight issues like size of data to be downloaded from server/webservice etc.,
FYI, our client service of Cassandra runs on port 9160..

Categories