return RedirectToAction("deshboardportal", "Portal",new { User_Id = Session["USER_ID"], RoleId = Session["ROLE_ID"]});
In this above code i want to only encrypt url parameter which is written below :-
new { User_Id = Session["USER_ID"], RoleId = Session["ROLE_ID"]}
You Can try
return RedirectToAction("deshboardportal", "Portal", new { User_Id = Encode(Session["USER_ID"].ToString()), RoleId = Encode(Session["ROLE_ID"].ToString()) });
public string Encode(string encodeMe)
{
byte[] encoded = System.Text.Encoding.UTF8.GetBytes(encodeMe);
return Convert.ToBase64String(encoded);
}
public static string Decode(string decodeMe)
{
byte[] encoded = Convert.FromBase64String(decodeMe);
return System.Text.Encoding.UTF8.GetString(encoded);
}
Related
I try Mictosoft example to create and and contact to exchange server using EWS and strangly mark as invalid while try using fax number for sending using Windows Fax and Scan (wfs.exe).
So , Does anybody know how should I set fax number in EWS that can be usable for sending fax in fax and scan?
After a lot of exprementing and invaestigating using OutlookSpy I found out I should add a # before number to be recognizable by Windows Fax and Scan. This is my final code.
public static ExchangeService GetService(string emailUser = defaultUser, string pass = defaultPass)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
//service.AutodiscoverUrl(emailUser, RedirectionUrlValidationCallback);
service.Url = new Uri("https://xs3.domain.net/EWS/Exchange.asmx");
service.Credentials = new WebCredentials(emailUser, pass);
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
return service;
}
public static bool IsValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
public static void AddOrUpdateContact(ExchangeService service, string id, Dictionary<string, string> dataRecord, string targetFolder = defaultCotactsFolder, bool faxOnly = false)
{
Folder parentFolder;
FindFoldersResults folderItems = service.FindFolders(
WellKnownFolderName.Contacts,//parent folder
new SearchFilter.IsEqualTo(FolderSchema.DisplayName, targetFolder),
new FolderView(1)// return first 1 records
);
if (folderItems != null && folderItems.Count() > 0)
{//folder found!
parentFolder = folderItems.First() as Folder;
}
else
{//folder NOT found!
return;
}
ExtendedPropertyDefinition CustomProperty = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "BusinessFax", MapiPropertyType.String);
FindItemsResults<Item> contactItems = service.FindItems(
parentFolder.Id,
new SearchFilter.IsEqualTo(ContactSchema.NickName, id),
new ItemView(1)
);
bool doesExist = contactItems != null && contactItems.Count() > 0;
Contact contact;
if (doesExist)
{//contact found!
contact = contactItems.First() as Contact;
}
else
{
// Create the contact.
contact = new Contact(service);
}
// Specify the name and how the contact should be filled.
contact.CompanyName = name;
contact.NickName = id;
contact.PhoneNumbers[PhoneNumberKey.BusinessFax] = "#"+dataRecord["COD_FAX_SUPID"];
contact.FileAsMapping = FileAsMapping.Company;
if (!faxOnly)
{
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = dataRecord["COD_TEL_SUPID"];
if (IsValidEmail(dataRecord["EMAIL_SUPID"]))
{
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress(dataRecord["EMAIL_SUPID"]);
}
contact.PhysicalAddresses[PhysicalAddressKey.Home] = new PhysicalAddressEntry()
{
Street = dataRecord["DES_STREET_SUPID"],
City = dataRecord["DES_TOWN_SUPID"],
CountryOrRegion = dataRecord["DES_COUNTRY_SUPID"],
PostalCode = dataRecord["COD_POST_SUPID"] + (String.IsNullOrWhiteSpace(dataRecord["NUM_BOX_SUPID"]) ? "" : $", PostBox: {dataRecord["NUM_BOX_SUPID"]}"),
}
}
if (doesExist)
{ //contact found!
contact.Update(ConflictResolutionMode.AlwaysOverwrite);
}
else
{
//save new!
contact.Save(parentFolder.Id);
}
}
Usage Example:
ExchangeService service = ContatctUpdaterLib.ContatcUpdater.GetService("USER#DONAMAIN.COM","123456");
//GetUserData return user data record as a Dictionary<string,string>
var data = GetUserData();
AddOrUpdateContact(service, dataRecord["COD_SUP_SUPID"], dataRecord, "Contacts(Fax Only)" ,true);
I have created an HTTP Client that sends data to my server. This data will query my server that will return a JSON object. How can I receive the JSON Object response from my server and insert it into my database?
The code below will send a ContactID to my server and my server will return a JSON Object How can I get the JSON Object from my server? What will I add to my code? I have added
var data = await response.Content.ReadAsStringAsync();
but I don't know how to proceed.
try
{
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var sql = "SELECT * FROM tblUser WHERE ContactID = '" + contact + "'";
var getUser = conn.QueryAsync<UserTable>(sql);
var resultCount = getUser.Result.Count;
//Check if the user has been sync
if (resultCount < 1)
{
try
{
syncStatus.Text = "Syncing user to server...";
var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=8qApc8";
string contentType = "application/json";
JObject json = new JObject
{
{ "ContactID", contact }
};
HttpClient client = new HttpClient();
var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
var data = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var userresult = JsonConvert.DeserializeObject<IList<UserData>>(content);
var count = userresult.Count;
for (int i = 0; i < count; i++)
{
try
{
syncStatus.Text = "Syncing user to server...";
var item = userresult[i];
var contactID = item.ContactID;
var userID = item.UserID;
var userPassword = item.UserPassword;
var userType = item.UserType;
var userStatus = item.UserStatus;
var lastSync = item.LastSync;
var serverUpdate = item.ServerUpdate;
var mobileUpdate = item.MobileUpdate;
var user = new UserTable
{
ContactID = Convert.ToInt32(contactID),
UserID = userID,
UserPassword = userPassword,
UserType = userType,
UserStatus = userStatus,
LastSync = lastSync,
ServerUpdate = serverUpdate,
MobileUpdate = mobileUpdate
};
await conn.InsertAsync(user);
}
catch (Exception ex)
{
Console.Write("Syncing user error " + ex.Message);
}
}
}
}
catch (Exception ex)
{
Console.Write("Syncing User Error " + ex.Message);
}
}
My PHP code will query my database with the ContactID received from Xamarin HTTP Client.
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$ContactID = $json_obj->ContactID;
$sql = "SELECT * FROM tblUser WHERE ContactID = '$ContactID'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
while ($row = #mysqli_fetch_array($result)) {
$decr = CryptRC4(FromHexDump($row['UserPassword']), $key);
$ar[] = array(
'ContactID' => $row['ContactID'],
'UserID' => $row['UserID'],
'UserPassword' => $decr,
'UserType' => $row['UserType'],
'UserStatus' => $row['UserStatus'],
'LastSync' => $sync,
'ServerUpdate' => $row['ServerUpdate'],
'MobileUpdate' => $row['MobileUpdate']
);
print json_encode($ar);
//Update LastSync DateTime
$sql = "UPDATE tblUser SET LastSync = '$sync' WHERE ContactID = '$ContactID'";
mysqli_query($conn, $sql);
}
}
Last statement in your example above gives list of json objects in string format.
var data = await response.Content.ReadAsStringAsync();
You need to convert that back to list of objects. To let your project know about definition of the object, create a plain class with public properties (Something like below)
public class UserLog
{
public int ContactId { get; set; }
public string Log { get; set; }
public DateTime LogDate { get; set; }
}
Add Newtonsoft.Json (by James Newton-King) Nuget package to your project so that you can work with json.
To convert content of the variable 'data' into list of UserLog objects, write code like
var list = NewtonsoftUtil<IList<UserLog>>.DeserializeObject(data);
(Add using Newtonsoft.Json; at top of the file)
Please let me know if this helps.
The answers above missing one important point -> efficiency.
There is no need to allocate a string in memory, especially if your JSON is big. Streams can do much better then strings:
// Read the response as stream
var stream = await response.Content.ReadAsStreamAsync();
// Use the next method for deserialization
T DeserializeJsonFromStream<T>(Stream stream)
{
if (stream == null || stream.CanRead == false)
return default(T);
using (var sr = new StreamReader(stream))
using (var jtr = new JsonTextReader(sr))
{
var js = new JsonSerializer();
return js.Deserialize<T>(jtr);
}
}
P.S.: Code example is bases on Json.NET.
P.S.S.: There are many good articles on this topic, I could recommend to get familiar with the next one.
Assuming that you have done everything correctly. In other words, You're be able to sent your contactID and get back a json.
Let's say your json structure is something like:
{"firstname" : "Doe",
"lastname" : "foo"
"age" : "27"}
One possible way to retrieve the data is as below:
using Newtonsoft.Json;
//after PostAsync()
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
JObject jContent = (JObject)JsonConvert.DeserializeObject(content);
string firstName = (string)jContent.GetValue("firstname")
string lastName = (string)jContent.GetValue("lastname");
int age = (int)jContent.GetValue("age");
}
Newtonsoft is available on Nuget. you need to install it if you have not done so.
Improved solution
What if your json has many key/values pairs like below:
{ key1 : value1,
key2 : value2,
key3 : value3,
...
key10 : value10}
Then it is not a good idea by doing :
string foo1 = (string)jContent.GetValue("key1");
string foo2 = (string)jContent.GetValue("key2");
//...
string foo10 = (string)jContent.GetValue("key10");
To handle this case, you can create a class:
public class Foo
{
public string Foo1 {get;set;}
public string Foo2 {get;set;}
//...
public string Foo2 {get;set;}
}
Then, you can do as simple as below:
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Foo foo = JsonConvert.DeserializeObject<Foo>(content);
}
The improved solution referecnced from www.newtonsoft.com. Go there and check out other ways of using the library.
here is my table:
table name: data
fields:
Id
category
description
imagePath
I'm building a webApi that returns all imagePath or by id.
web api controller:
namespace task.Controllers
{
public class ImagesController : ApiController
{
DataEntry db = new DataEntry();
public IEnumerable<datum> GetImages()
{
var imagePath = from m in db.data select m;
return imagePath;
}
public IHttpActionResult GetImages(int id)
{
var imagePath = from m in db.data select m;
var imagPath = imagePath.Where((p) => p.Id == id);
if (imagePath == null)
{
return NotFound();
}
return Ok(imagePath);
}
}
}
It's returning all fields (Id,category, description and imagePath) instead of imagePath only.and for the select by Id method it's not working also, so what is wrong??
For the imagePath, try specifying it in the linq query like so:
public IEnumerable<string> GetImages()
{
var imagePath = from m in db.data select m.imagePath;
return imagePath.ToList();
}
For the select by id, try this:
public string GetImages(int id)
{
var imagePath = from m in db.data select m;
var imagPath = imagePath.Where((p) => p.Id == id);
if (imagPath == null)
{
return NotFound();
}
return Ok(imagPath.imagePath);
}
Double check for typo such as imagPath and imagePath too
I was wondering the best way of accessing the a user's AuthSession from within a custom validator we have hooked up via the servicestack's fluent-validation API hooks. Basically, the requirements are forcing us to access the database through this validator using a class called "DocNumberValidator ". The user's Id is saved into session when they authenticate, down the line we need this information to complete a successful SQL query. How does one access this session information (see below....). The IoC container does not have reference to the AuthSession?
I guess the question is, how does someone pass the necessary session value into a class invoked by SS validation framework?
Sample Code :
public class MyValidator : AbstractValidator<Statuses>
{
public IDocNumberValidator DocNumberValidator { get; set; }
public StatusesValidator()
{
RuleFor(s => s.DocNumber)
.Must(docNum => this.DocNumberValidator.Validate(docNum))
.WithMessage("Document Number is invalid.")
.WithErrorCode("S-001");
}
}
public class DocNumberValidator : IDocNumberValidator
{
public IDbConnectionFactory Db { get; set; }
public bool Validate(string docNum)
{
var isFound = false;
this.Db.Run(conn =>
{
var sql = "SELECT COUNT([docNumber]) FROM [TABLE] WHERE [docNumber] = #DocNum AND [UserId] = #UserID";
var cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.Add(new SqlParameter("#DocNum", docNum));
cmd.Parameters.Add(new SqlParameter("#UserID", ????????)); // how does one get access to saved users session here
int cnt = (int) cmd.ExecuteScalar();
if (cnt == 1)
isFound = true;
});
return isFound;
}
}
Not really sure this is the best way to do it. Open to suggestions.
Use SessionFeature.GetSessionKey() to get the session key
Add public ICacheClient CacheClient { get; set; } to the validator.
Will be injected by IoC container
Get the AuthUserSession (or whatever type you're using) from the
cache using the key
Added into your example
public class DocNumberValidator : IDocNumberValidator
{
public IDbConnectionFactory Db { get; set; }
public ICacheClient CacheClient { get; set; }
public bool Validate(string docNum)
{
var isFound = false;
var sessionKey = SessionFeature.GetSessionKey();
var user = CacheClient.Get<AuthUserSession>(sessionKey); //Use whatever class you stored in the session
this.Db.Run(conn =>
{
var sql = "SELECT COUNT([docNumber]) FROM [TABLE] WHERE [docNumber] = #DocNum AND [UserId] = #UserID";
var cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.Add(new SqlParameter("#DocNum", docNum));
cmd.Parameters.Add(new SqlParameter("#UserID", user.UserAuthId)); // user whatever property you need access to
int cnt = (int) cmd.ExecuteScalar();
if (cnt == 1)
isFound = true;
});
return isFound;
}
}
I want to replicate what StackOverflow does with its URLs.
For example:
Hidden Features of C#? - (Hidden Features of C#?)
or
Hidden Features of C#? - (Hidden Features of C#?)
Will Take you to the same page but when they return to the browser the first one is always returned.
How do you implement the change so the larger URL is returned?
The way that I've handled this before is to have two routes, registered in this order
routes.MapRoute(
null,
"questions/{id}/{title}",
new { controller = "Questions", action = "Index" },
new { id = #"\d+", title = #"[\w\-]*" });
routes.MapRoute(
null,
"questions/{id}",
new { controller = "Questions", action = "Index" },
new { id = #"\d+" });
now in the controller action,
public class QuestionsController
{
private readonly IQuestionRepository _questionRepo;
public QuestionsController(IQuestionRepository questionRepo)
{
_questionRepo = questionRepo;
}
public ActionResult Index(int id, string title)
{
var question = _questionRepo.Get(id);
if (string.IsNullOrWhiteSpace(title) || title != question.Title.ToSlug())
{
return RedirectToAction("Index", new { id, title = question.Title.ToSlug() }).AsMovedPermanently();
}
return View(question);
}
}
We'll permanently redirect to the URL that contains the title slug (lowercase title with hyphens as separators) if we only have the id. We also make sure that the title passed is the correct one by checking it against the slugged version of the question title, thereby creating a canonical URL for the question that contains both the id and the correct title slug.
A couple of the helpers used
public static class PermanentRedirectionExtensions
{
public static PermanentRedirectToRouteResult AsMovedPermanently
(this RedirectToRouteResult redirection)
{
return new PermanentRedirectToRouteResult(redirection);
}
}
public class PermanentRedirectToRouteResult : ActionResult
{
public RedirectToRouteResult Redirection { get; private set; }
public PermanentRedirectToRouteResult(RedirectToRouteResult redirection)
{
this.Redirection = redirection;
}
public override void ExecuteResult(ControllerContext context)
{
// After setting up a normal redirection, switch it to a 301
Redirection.ExecuteResult(context);
context.HttpContext.Response.StatusCode = 301;
context.HttpContext.Response.Status = "301 Moved Permanently";
}
}
public static class StringExtensions
{
private static readonly Encoding Encoding = Encoding.GetEncoding("Cyrillic");
public static string RemoveAccent(this string value)
{
byte[] bytes = Encoding.GetBytes(value);
return Encoding.ASCII.GetString(bytes);
}
public static string ToSlug(this string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return string.Empty;
}
var str = value.RemoveAccent().ToLowerInvariant();
str = Regex.Replace(str, #"[^a-z0-9\s-]", "");
str = Regex.Replace(str, #"\s+", " ").Trim();
str = str.Substring(0, str.Length <= 200 ? str.Length : 200).Trim();
str = Regex.Replace(str, #"\s", "-");
str = Regex.Replace(str, #"-+", "-");
return str;
}
}