text stringlengths 13 6.01M |
|---|
using System;
using Atlas;
using CoreGraphics;
using CoreLocation;
using Foundation;
using ObjCRuntime;
using UIKit;
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLAddressBarPartAttributeName;
[Field ("ATLAddressBarPartAttributeName", "__Internal")]
NSString ATLAddressBarPartAttributeName { get; }
// extern NSString *const ATLAddressBarNamePart;
[Field ("ATLAddressBarNamePart", "__Internal")]
NSString ATLAddressBarNamePart { get; }
// extern NSString *const ATLAddressBarDelimiterPart;
[Field ("ATLAddressBarDelimiterPart", "__Internal")]
NSString ATLAddressBarDelimiterPart { get; }
// extern const CGFloat ATLAddressBarTextViewIndent;
[Field ("ATLAddressBarTextViewIndent", "__Internal")]
nfloat ATLAddressBarTextViewIndent { get; }
// extern const CGFloat ATLAddressBarTextContainerInset;
[Field ("ATLAddressBarTextContainerInset", "__Internal")]
nfloat ATLAddressBarTextContainerInset { get; }
}
// @interface ATLAddressBarTextView : UITextView
[BaseType (typeof(UITextView))]
interface ATLAddressBarTextView
{
// @property (nonatomic) UIFont * addressBarFont __attribute__((annotate("ui_appearance_selector")));
[Export ("addressBarFont", ArgumentSemantic.Assign)]
UIFont AddressBarFont { get; set; }
// @property (nonatomic) UIColor * addressBarTextColor __attribute__((annotate("ui_appearance_selector")));
[Export ("addressBarTextColor", ArgumentSemantic.Assign)]
UIColor AddressBarTextColor { get; set; }
// @property (nonatomic) UIColor * addressBarHighlightColor __attribute__((annotate("ui_appearance_selector")));
[Export ("addressBarHighlightColor", ArgumentSemantic.Assign)]
UIColor AddressBarHighlightColor { get; set; }
}
// @interface ATLAddressBarView : UIView
[BaseType (typeof(UIView))]
interface ATLAddressBarView
{
// @property (nonatomic) ATLAddressBarTextView * addressBarTextView;
[Export ("addressBarTextView", ArgumentSemantic.Assign)]
ATLAddressBarTextView AddressBarTextView { get; set; }
// @property (nonatomic) UIButton * addContactsButton;
[Export ("addContactsButton", ArgumentSemantic.Assign)]
UIButton AddContactsButton { get; set; }
}
// @protocol ATLAvatarItem <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLAvatarItem
{
// @required @property (readonly, nonatomic) NSURL * avatarImageURL;
[Export ("avatarImageURL")]
NSUrl AvatarImageURL { get; }
// @required @property (readonly, nonatomic) UIImage * avatarImage;
[Export ("avatarImage")]
UIImage AvatarImage { get; }
// @required @property (readonly, nonatomic) NSString * avatarInitials;
[Export ("avatarInitials")]
string AvatarInitials { get; }
}
// @protocol ATLParticipant <NSObject, ATLAvatarItem>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLParticipant : IATLAvatarItem
{
// @required @property (readonly, nonatomic) NSString * firstName;
[Export ("firstName")]
string FirstName { get; }
// @required @property (readonly, nonatomic) NSString * lastName;
[Export ("lastName")]
string LastName { get; }
// @required @property (readonly, nonatomic) NSString * fullName;
[Export ("fullName")]
string FullName { get; }
// @required @property (readonly, nonatomic) NSString * participantIdentifier;
[Export ("participantIdentifier")]
string ParticipantIdentifier { get; }
}
// @protocol ATLAddressBarViewControllerDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLAddressBarViewControllerDelegate
{
// @optional -(void)addressBarViewControllerDidBeginSearching:(ATLAddressBarViewController *)addressBarViewController;
[Export ("addressBarViewControllerDidBeginSearching:")]
void AddressBarViewControllerDidBeginSearching (ATLAddressBarViewController addressBarViewController);
// @optional -(void)addressBarViewController:(ATLAddressBarViewController *)addressBarViewController didSelectParticipant:(id<ATLParticipant>)participant;
[Export ("addressBarViewController:didSelectParticipant:")]
void AddressBarViewController (ATLAddressBarViewController addressBarViewController, ATLParticipant participant);
// @optional -(void)addressBarViewController:(ATLAddressBarViewController *)addressBarViewController didRemoveParticipant:(id<ATLParticipant>)participant;
[Export ("addressBarViewController:didRemoveParticipant:")]
void AddressBarViewController (ATLAddressBarViewController addressBarViewController, ATLParticipant participant);
// @optional -(void)addressBarViewControllerDidEndSearching:(ATLAddressBarViewController *)addressBarViewController;
[Export ("addressBarViewControllerDidEndSearching:")]
void AddressBarViewControllerDidEndSearching (ATLAddressBarViewController addressBarViewController);
// @optional -(void)addressBarViewController:(ATLAddressBarViewController *)addressBarViewController didTapAddContactsButton:(UIButton *)addContactsButton;
[Export ("addressBarViewController:didTapAddContactsButton:")]
void AddressBarViewController (ATLAddressBarViewController addressBarViewController, UIButton addContactsButton);
// @optional -(void)addressBarViewControllerDidSelectWhileDisabled:(ATLAddressBarViewController *)addressBarViewController;
[Export ("addressBarViewControllerDidSelectWhileDisabled:")]
void AddressBarViewControllerDidSelectWhileDisabled (ATLAddressBarViewController addressBarViewController);
// @optional -(void)addressBarViewController:(ATLAddressBarViewController *)addressBarViewController searchForParticipantsMatchingText:(NSString *)searchText completion:(void (^)(NSArray *))completion;
[Export ("addressBarViewController:searchForParticipantsMatchingText:completion:")]
void AddressBarViewController (ATLAddressBarViewController addressBarViewController, string searchText, Action<NSArray> completion);
}
// @interface ATLAddressBarViewController : UIViewController
[BaseType (typeof(UIViewController))]
interface ATLAddressBarViewController
{
[Wrap ("WeakDelegate")]
[NullAllowed]
ATLAddressBarViewControllerDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<ATLAddressBarViewControllerDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (nonatomic) ATLAddressBarView * addressBarView;
[Export ("addressBarView", ArgumentSemantic.Assign)]
ATLAddressBarView AddressBarView { get; set; }
// @property (nonatomic) NSOrderedSet * selectedParticipants;
[Export ("selectedParticipants", ArgumentSemantic.Assign)]
NSOrderedSet SelectedParticipants { get; set; }
// -(void)selectParticipant:(id<ATLParticipant>)participant;
[Export ("selectParticipant:")]
void SelectParticipant (ATLParticipant participant);
// -(void)reloadView;
[Export ("reloadView")]
void ReloadView ();
// -(void)disable;
[Export ("disable")]
void Disable ();
// -(BOOL)isDisabled;
[Export ("isDisabled")]
[Verify (MethodToProperty)]
bool IsDisabled { get; }
}
// @protocol ATLConversationPresenting <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLConversationPresenting
{
// @required -(void)presentConversation:(id)conversation;
[Abstract]
[Export ("presentConversation:")]
void PresentConversation (NSObject conversation);
// @required -(void)updateWithConversationTitle:(NSString *)conversationTitle;
[Abstract]
[Export ("updateWithConversationTitle:")]
void UpdateWithConversationTitle (string conversationTitle);
// @required -(void)updateWithAvatarItem:(id<ATLAvatarItem>)avatarItem;
[Abstract]
[Export ("updateWithAvatarItem:")]
void UpdateWithAvatarItem (ATLAvatarItem avatarItem);
// @required -(void)updateWithLastMessageText:(NSString *)lastMessageText;
[Abstract]
[Export ("updateWithLastMessageText:")]
void UpdateWithLastMessageText (string lastMessageText);
}
// @interface ATLConversationTableViewCell : UITableViewCell <ATLConversationPresenting>
[BaseType (typeof(UITableViewCell))]
interface ATLConversationTableViewCell : IATLConversationPresenting
{
// @property (nonatomic) UIFont * conversationTitleLabelFont __attribute__((annotate("ui_appearance_selector")));
[Export ("conversationTitleLabelFont", ArgumentSemantic.Assign)]
UIFont ConversationTitleLabelFont { get; set; }
// @property (nonatomic) UIColor * conversationTitleLabelColor __attribute__((annotate("ui_appearance_selector")));
[Export ("conversationTitleLabelColor", ArgumentSemantic.Assign)]
UIColor ConversationTitleLabelColor { get; set; }
// @property (nonatomic) UIFont * lastMessageLabelFont __attribute__((annotate("ui_appearance_selector")));
[Export ("lastMessageLabelFont", ArgumentSemantic.Assign)]
UIFont LastMessageLabelFont { get; set; }
// @property (nonatomic) UIColor * lastMessageLabelColor __attribute__((annotate("ui_appearance_selector")));
[Export ("lastMessageLabelColor", ArgumentSemantic.Assign)]
UIColor LastMessageLabelColor { get; set; }
// @property (nonatomic) UIFont * dateLabelFont __attribute__((annotate("ui_appearance_selector")));
[Export ("dateLabelFont", ArgumentSemantic.Assign)]
UIFont DateLabelFont { get; set; }
// @property (nonatomic) UIColor * dateLabelColor __attribute__((annotate("ui_appearance_selector")));
[Export ("dateLabelColor", ArgumentSemantic.Assign)]
UIColor DateLabelColor { get; set; }
// @property (nonatomic) UIColor * unreadMessageIndicatorBackgroundColor __attribute__((annotate("ui_appearance_selector")));
[Export ("unreadMessageIndicatorBackgroundColor", ArgumentSemantic.Assign)]
UIColor UnreadMessageIndicatorBackgroundColor { get; set; }
// @property (nonatomic) UIColor * cellBackgroundColor __attribute__((annotate("ui_appearance_selector")));
[Export ("cellBackgroundColor", ArgumentSemantic.Assign)]
UIColor CellBackgroundColor { get; set; }
}
// @protocol ATLConversationListViewControllerDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLConversationListViewControllerDelegate
{
// @required -(void)conversationListViewController:(ATLConversationListViewController *)conversationListViewController didSelectConversation:(id)conversation;
[Abstract]
[Export ("conversationListViewController:didSelectConversation:")]
void DidSelectConversation (ATLConversationListViewController conversationListViewController, NSObject conversation);
// @optional -(void)conversationListViewController:(ATLConversationListViewController *)conversationListViewController didDeleteConversation:(id)conversation deletionMode:(id)deletionMode;
[Export ("conversationListViewController:didDeleteConversation:deletionMode:")]
void DidDeleteConversation (ATLConversationListViewController conversationListViewController, NSObject conversation, NSObject deletionMode);
// @optional -(void)conversationListViewController:(ATLConversationListViewController *)conversationListViewController didFailDeletingConversation:(id)conversation deletionMode:(id)deletionMode error:(NSError *)error;
[Export ("conversationListViewController:didFailDeletingConversation:deletionMode:error:")]
void DidFailDeletingConversation (ATLConversationListViewController conversationListViewController, NSObject conversation, NSObject deletionMode, NSError error);
// @optional -(void)conversationListViewController:(ATLConversationListViewController *)conversationListViewController didSearchForText:(NSString *)searchText completion:(void (^)(NSSet *))completion;
[Export ("conversationListViewController:didSearchForText:completion:")]
void DidSearchForText (ATLConversationListViewController conversationListViewController, string searchText, Action<NSSet> completion);
}
// @protocol ATLConversationListViewControllerDataSource <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLConversationListViewControllerDataSource
{
// @required -(NSString *)conversationListViewController:(ATLConversationListViewController *)conversationListViewController titleForConversation:(id)conversation;
[Abstract]
[Export ("conversationListViewController:titleForConversation:")]
string ConversationListViewController (ATLConversationListViewController conversationListViewController, NSObject conversation);
// @optional -(id<ATLAvatarItem>)conversationListViewController:(ATLConversationListViewController *)conversationListViewController avatarItemForConversation:(id)conversation;
[Export ("conversationListViewController:avatarItemForConversation:")]
ATLAvatarItem ConversationListViewController (ATLConversationListViewController conversationListViewController, NSObject conversation);
// @optional -(NSString *)reuseIdentifierForConversationListViewController:(ATLConversationListViewController *)conversationListViewController;
[Export ("reuseIdentifierForConversationListViewController:")]
string ReuseIdentifierForConversationListViewController (ATLConversationListViewController conversationListViewController);
// @optional -(NSString *)conversationListViewController:(ATLConversationListViewController *)conversationListViewController textForButtonWithDeletionMode:(id)deletionMode;
[Export ("conversationListViewController:textForButtonWithDeletionMode:")]
string ConversationListViewController (ATLConversationListViewController conversationListViewController, NSObject deletionMode);
// @optional -(UIColor *)conversationListViewController:(ATLConversationListViewController *)conversationListViewController colorForButtonWithDeletionMode:(id)deletionMode;
[Export ("conversationListViewController:colorForButtonWithDeletionMode:")]
UIColor ConversationListViewController (ATLConversationListViewController conversationListViewController, NSObject deletionMode);
// @optional -(NSString *)conversationListViewController:(ATLConversationListViewController *)conversationListViewController lastMessageTextForConversation:(id)conversation;
[Export ("conversationListViewController:lastMessageTextForConversation:")]
string ConversationListViewController (ATLConversationListViewController conversationListViewController, NSObject conversation);
// @optional -(id)conversationListViewController:(ATLConversationListViewController *)viewController willLoadWithQuery:(id)defaultQuery;
[Export ("conversationListViewController:willLoadWithQuery:")]
NSObject ConversationListViewController (ATLConversationListViewController viewController, NSObject defaultQuery);
}
// @interface ATLConversationListViewController : UITableViewController
[BaseType (typeof(UITableViewController))]
interface ATLConversationListViewController
{
// +(instancetype)conversationListViewControllerWithLayerClient:(id)layerClient;
[Static]
[Export ("conversationListViewControllerWithLayerClient:")]
ATLConversationListViewController ConversationListViewControllerWithLayerClient (NSObject layerClient);
// -(instancetype)initWithLayerClient:(id)layerClient;
[Export ("initWithLayerClient:")]
IntPtr Constructor (NSObject layerClient);
// @property (nonatomic) int * layerClient;
[Export ("layerClient", ArgumentSemantic.Assign)]
unsafe int* LayerClient { get; set; }
// @property (readonly, nonatomic) int * queryController;
[Export ("queryController")]
unsafe int* QueryController { get; }
[Wrap ("WeakDelegate")]
[NullAllowed]
ATLConversationListViewControllerDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<ATLConversationListViewControllerDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (nonatomic, weak) id<ATLConversationListViewControllerDataSource> _Nullable dataSource;
[NullAllowed, Export ("dataSource", ArgumentSemantic.Weak)]
ATLConversationListViewControllerDataSource DataSource { get; set; }
// @property (nonatomic) Class<ATLConversationPresenting> cellClass;
[Export ("cellClass", ArgumentSemantic.Assign)]
ATLConversationPresenting CellClass { get; set; }
// @property (nonatomic) NSArray * deletionModes;
[Export ("deletionModes", ArgumentSemantic.Assign)]
[Verify (StronglyTypedNSArray)]
NSObject[] DeletionModes { get; set; }
// @property (assign, nonatomic) BOOL displaysAvatarItem;
[Export ("displaysAvatarItem")]
bool DisplaysAvatarItem { get; set; }
// @property (assign, nonatomic) BOOL allowsEditing;
[Export ("allowsEditing")]
bool AllowsEditing { get; set; }
// @property (assign, nonatomic) CGFloat rowHeight;
[Export ("rowHeight")]
nfloat RowHeight { get; set; }
// @property (readonly, nonatomic) UISearchDisplayController * searchController;
[Export ("searchController")]
UISearchDisplayController SearchController { get; }
// @property (assign, nonatomic) BOOL shouldDisplaySearchController;
[Export ("shouldDisplaySearchController")]
bool ShouldDisplaySearchController { get; set; }
// -(void)reloadCellForConversation:(id)conversation;
[Export ("reloadCellForConversation:")]
void ReloadCellForConversation (NSObject conversation);
}
// @interface ATLMessageComposeTextView : UITextView
[BaseType (typeof(UITextView))]
interface ATLMessageComposeTextView
{
// @property (nonatomic) NSString * placeholder;
[Export ("placeholder")]
string Placeholder { get; set; }
// @property (nonatomic, weak) UIResponder * _Nullable overrideNextResponder;
[NullAllowed, Export ("overrideNextResponder", ArgumentSemantic.Weak)]
UIResponder OverrideNextResponder { get; set; }
}
// @interface ATLMediaAttachment : NSTextAttachment
[BaseType (typeof(NSTextAttachment))]
interface ATLMediaAttachment
{
// +(instancetype)mediaAttachmentWithAssetURL:(NSURL *)assetURL thumbnailSize:(NSUInteger)thumbnailSize;
[Static]
[Export ("mediaAttachmentWithAssetURL:thumbnailSize:")]
ATLMediaAttachment MediaAttachmentWithAssetURL (NSUrl assetURL, nuint thumbnailSize);
// +(instancetype)mediaAttachmentWithImage:(UIImage *)image metadata:(NSDictionary *)metadata thumbnailSize:(NSUInteger)thumbnailSize;
[Static]
[Export ("mediaAttachmentWithImage:metadata:thumbnailSize:")]
ATLMediaAttachment MediaAttachmentWithImage (UIImage image, NSDictionary metadata, nuint thumbnailSize);
// +(instancetype)mediaAttachmentWithFileURL:(NSURL *)fileURL thumbnailSize:(NSUInteger)thumbnailSize;
[Static]
[Export ("mediaAttachmentWithFileURL:thumbnailSize:")]
ATLMediaAttachment MediaAttachmentWithFileURL (NSUrl fileURL, nuint thumbnailSize);
// +(instancetype)mediaAttachmentWithText:(NSString *)text;
[Static]
[Export ("mediaAttachmentWithText:")]
ATLMediaAttachment MediaAttachmentWithText (string text);
// +(instancetype)mediaAttachmentWithLocation:(CLLocation *)location;
[Static]
[Export ("mediaAttachmentWithLocation:")]
ATLMediaAttachment MediaAttachmentWithLocation (CLLocation location);
// @property (readonly, nonatomic) ATLMediaAttachmentType mediaType;
[Export ("mediaType")]
ATLMediaAttachmentType MediaType { get; }
// @property (readonly, nonatomic) NSUInteger thumbnailSize;
[Export ("thumbnailSize")]
nuint ThumbnailSize { get; }
// @property (assign, nonatomic) CGSize maximumInputSize;
[Export ("maximumInputSize", ArgumentSemantic.Assign)]
CGSize MaximumInputSize { get; set; }
// @property (readonly, nonatomic) NSString * textRepresentation;
[Export ("textRepresentation")]
string TextRepresentation { get; }
// @property (readonly, nonatomic) NSString * mediaMIMEType;
[Export ("mediaMIMEType")]
string MediaMIMEType { get; }
// @property (readonly, nonatomic) NSInputStream * mediaInputStream;
[Export ("mediaInputStream")]
NSInputStream MediaInputStream { get; }
// @property (readonly, nonatomic) NSString * thumbnailMIMEType;
[Export ("thumbnailMIMEType")]
string ThumbnailMIMEType { get; }
// @property (readonly, nonatomic) NSInputStream * thumbnailInputStream;
[Export ("thumbnailInputStream")]
NSInputStream ThumbnailInputStream { get; }
// @property (readonly, nonatomic) NSString * metadataMIMEType;
[Export ("metadataMIMEType")]
string MetadataMIMEType { get; }
// @property (readonly, nonatomic) NSInputStream * metadataInputStream;
[Export ("metadataInputStream")]
NSInputStream MetadataInputStream { get; }
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLMessageInputToolbarDidChangeHeightNotification;
[Field ("ATLMessageInputToolbarDidChangeHeightNotification", "__Internal")]
NSString ATLMessageInputToolbarDidChangeHeightNotification { get; }
// extern NSString *const ATLMessageInputToolbarAccessibilityLabel;
[Field ("ATLMessageInputToolbarAccessibilityLabel", "__Internal")]
NSString ATLMessageInputToolbarAccessibilityLabel { get; }
}
// @protocol ATLMessageInputToolbarDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLMessageInputToolbarDelegate
{
// @required -(void)messageInputToolbar:(ATLMessageInputToolbar *)messageInputToolbar didTapRightAccessoryButton:(UIButton *)rightAccessoryButton;
[Abstract]
[Export ("messageInputToolbar:didTapRightAccessoryButton:")]
void MessageInputToolbar (ATLMessageInputToolbar messageInputToolbar, UIButton rightAccessoryButton);
// @required -(void)messageInputToolbar:(ATLMessageInputToolbar *)messageInputToolbar didTapLeftAccessoryButton:(UIButton *)leftAccessoryButton;
[Abstract]
[Export ("messageInputToolbar:didTapLeftAccessoryButton:")]
void MessageInputToolbar (ATLMessageInputToolbar messageInputToolbar, UIButton leftAccessoryButton);
// @optional -(void)messageInputToolbarDidType:(ATLMessageInputToolbar *)messageInputToolbar;
[Export ("messageInputToolbarDidType:")]
void MessageInputToolbarDidType (ATLMessageInputToolbar messageInputToolbar);
// @optional -(void)messageInputToolbarDidEndTyping:(ATLMessageInputToolbar *)messageInputToolbar;
[Export ("messageInputToolbarDidEndTyping:")]
void MessageInputToolbarDidEndTyping (ATLMessageInputToolbar messageInputToolbar);
}
// @interface ATLMessageInputToolbar : UIToolbar
[BaseType (typeof(UIToolbar))]
interface ATLMessageInputToolbar
{
// -(void)insertMediaAttachment:(ATLMediaAttachment *)mediaAttachment withEndLineBreak:(BOOL)endLineBreak;
[Export ("insertMediaAttachment:withEndLineBreak:")]
void InsertMediaAttachment (ATLMediaAttachment mediaAttachment, bool endLineBreak);
// @property (nonatomic) UIButton * leftAccessoryButton;
[Export ("leftAccessoryButton", ArgumentSemantic.Assign)]
UIButton LeftAccessoryButton { get; set; }
// @property (nonatomic) UIButton * rightAccessoryButton;
[Export ("rightAccessoryButton", ArgumentSemantic.Assign)]
UIButton RightAccessoryButton { get; set; }
// @property (nonatomic) NSString * rightAccessoryButtonTitle;
[Export ("rightAccessoryButtonTitle")]
string RightAccessoryButtonTitle { get; set; }
// @property (nonatomic) UIColor * rightAccessoryButtonActiveColor __attribute__((annotate("ui_appearance_selector")));
[Export ("rightAccessoryButtonActiveColor", ArgumentSemantic.Assign)]
UIColor RightAccessoryButtonActiveColor { get; set; }
// @property (nonatomic) UIColor * rightAccessoryButtonDisabledColor __attribute__((annotate("ui_appearance_selector")));
[Export ("rightAccessoryButtonDisabledColor", ArgumentSemantic.Assign)]
UIColor RightAccessoryButtonDisabledColor { get; set; }
// @property (nonatomic) UIFont * rightAccessoryButtonFont __attribute__((annotate("ui_appearance_selector")));
[Export ("rightAccessoryButtonFont", ArgumentSemantic.Assign)]
UIFont RightAccessoryButtonFont { get; set; }
// @property (nonatomic) UIImage * leftAccessoryImage;
[Export ("leftAccessoryImage", ArgumentSemantic.Assign)]
UIImage LeftAccessoryImage { get; set; }
// @property (nonatomic) UIImage * rightAccessoryImage;
[Export ("rightAccessoryImage", ArgumentSemantic.Assign)]
UIImage RightAccessoryImage { get; set; }
// @property (nonatomic) BOOL displaysRightAccessoryImage;
[Export ("displaysRightAccessoryImage")]
bool DisplaysRightAccessoryImage { get; set; }
// @property (nonatomic) ATLMessageComposeTextView * textInputView;
[Export ("textInputView", ArgumentSemantic.Assign)]
ATLMessageComposeTextView TextInputView { get; set; }
// @property (nonatomic) CGFloat verticalMargin;
[Export ("verticalMargin")]
nfloat VerticalMargin { get; set; }
[Wrap ("WeakInputToolBarDelegate")]
[NullAllowed]
ATLMessageInputToolbarDelegate InputToolBarDelegate { get; set; }
// @property (nonatomic, weak) id<ATLMessageInputToolbarDelegate> _Nullable inputToolBarDelegate;
[NullAllowed, Export ("inputToolBarDelegate", ArgumentSemantic.Weak)]
NSObject WeakInputToolBarDelegate { get; set; }
// @property (nonatomic) NSUInteger maxNumberOfLines;
[Export ("maxNumberOfLines")]
nuint MaxNumberOfLines { get; set; }
// @property (readonly, nonatomic) NSArray * mediaAttachments;
[Export ("mediaAttachments")]
[Verify (StronglyTypedNSArray)]
NSObject[] MediaAttachments { get; }
// @property (nonatomic, weak) UIViewController * _Nullable containerViewController;
[NullAllowed, Export ("containerViewController", ArgumentSemantic.Weak)]
UIViewController ContainerViewController { get; set; }
}
// @interface ATLTypingIndicatorViewController : UIViewController
[BaseType (typeof(UIViewController))]
interface ATLTypingIndicatorViewController
{
// -(void)updateWithParticipants:(NSOrderedSet *)participants animated:(BOOL)animated;
[Export ("updateWithParticipants:animated:")]
void UpdateWithParticipants (NSOrderedSet participants, bool animated);
}
// @interface ATLBaseConversationViewController : UIViewController
[BaseType (typeof(UIViewController))]
interface ATLBaseConversationViewController
{
// @property (nonatomic) ATLAddressBarViewController * addressBarController;
[Export ("addressBarController", ArgumentSemantic.Assign)]
ATLAddressBarViewController AddressBarController { get; set; }
// @property (nonatomic) ATLMessageInputToolbar * messageInputToolbar;
[Export ("messageInputToolbar", ArgumentSemantic.Assign)]
ATLMessageInputToolbar MessageInputToolbar { get; set; }
// @property (nonatomic) ATLTypingIndicatorViewController * typingIndicatorController;
[Export ("typingIndicatorController", ArgumentSemantic.Assign)]
ATLTypingIndicatorViewController TypingIndicatorController { get; set; }
// @property (nonatomic) UICollectionView * collectionView;
[Export ("collectionView", ArgumentSemantic.Assign)]
UICollectionView CollectionView { get; set; }
// @property (nonatomic) CGFloat typingIndicatorInset;
[Export ("typingIndicatorInset")]
nfloat TypingIndicatorInset { get; set; }
// @property (nonatomic) BOOL displaysAddressBar;
[Export ("displaysAddressBar")]
bool DisplaysAddressBar { get; set; }
// -(ATLMessageInputToolbar *)initializeMessageInputToolbar;
[Export ("initializeMessageInputToolbar")]
[Verify (MethodToProperty)]
ATLMessageInputToolbar InitializeMessageInputToolbar { get; }
// -(BOOL)shouldScrollToBottom;
[Export ("shouldScrollToBottom")]
[Verify (MethodToProperty)]
bool ShouldScrollToBottom { get; }
// -(void)scrollToBottomAnimated:(BOOL)animated;
[Export ("scrollToBottomAnimated:")]
void ScrollToBottomAnimated (bool animated);
// -(CGPoint)bottomOffsetForContentSize:(CGSize)contentSize;
[Export ("bottomOffsetForContentSize:")]
CGPoint BottomOffsetForContentSize (CGSize contentSize);
}
// @protocol ATLConversationViewControllerDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLConversationViewControllerDelegate
{
// @optional -(void)conversationViewController:(ATLConversationViewController *)viewController didSendMessage:(id)message;
[Export ("conversationViewController:didSendMessage:")]
void ConversationViewController (ATLConversationViewController viewController, NSObject message);
// @optional -(void)conversationViewController:(ATLConversationViewController *)viewController didFailSendingMessage:(id)message error:(NSError *)error;
[Export ("conversationViewController:didFailSendingMessage:error:")]
void ConversationViewController (ATLConversationViewController viewController, NSObject message, NSError error);
// @optional -(void)conversationViewController:(ATLConversationViewController *)viewController didSelectMessage:(id)message;
[Export ("conversationViewController:didSelectMessage:")]
void ConversationViewController (ATLConversationViewController viewController, NSObject message);
// @optional -(CGFloat)conversationViewController:(ATLConversationViewController *)viewController heightForMessage:(id)message withCellWidth:(CGFloat)cellWidth;
[Export ("conversationViewController:heightForMessage:withCellWidth:")]
nfloat ConversationViewController (ATLConversationViewController viewController, NSObject message, nfloat cellWidth);
// @optional -(void)conversationViewController:(ATLConversationViewController *)conversationViewController configureCell:(UICollectionViewCell<ATLMessagePresenting> *)cell forMessage:(id)message;
[Export ("conversationViewController:configureCell:forMessage:")]
void ConversationViewController (ATLConversationViewController conversationViewController, ATLMessagePresenting cell, NSObject message);
// @optional -(NSOrderedSet *)conversationViewController:(ATLConversationViewController *)viewController messagesForMediaAttachments:(NSArray *)mediaAttachments;
[Export ("conversationViewController:messagesForMediaAttachments:")]
[Verify (StronglyTypedNSArray)]
NSOrderedSet ConversationViewController (ATLConversationViewController viewController, NSObject[] mediaAttachments);
}
// @protocol ATLConversationViewControllerDataSource <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLConversationViewControllerDataSource
{
// @required -(id<ATLParticipant>)conversationViewController:(ATLConversationViewController *)conversationViewController participantForIdentifier:(NSString *)participantIdentifier;
[Abstract]
[Export ("conversationViewController:participantForIdentifier:")]
ATLParticipant ConversationViewController (ATLConversationViewController conversationViewController, string participantIdentifier);
// @required -(NSAttributedString *)conversationViewController:(ATLConversationViewController *)conversationViewController attributedStringForDisplayOfDate:(NSDate *)date;
[Abstract]
[Export ("conversationViewController:attributedStringForDisplayOfDate:")]
NSAttributedString ConversationViewController (ATLConversationViewController conversationViewController, NSDate date);
// @required -(NSAttributedString *)conversationViewController:(ATLConversationViewController *)conversationViewController attributedStringForDisplayOfRecipientStatus:(NSDictionary *)recipientStatus;
[Abstract]
[Export ("conversationViewController:attributedStringForDisplayOfRecipientStatus:")]
NSAttributedString ConversationViewController (ATLConversationViewController conversationViewController, NSDictionary recipientStatus);
// @optional -(NSString *)conversationViewController:(ATLConversationViewController *)viewController reuseIdentifierForMessage:(id)message;
[Export ("conversationViewController:reuseIdentifierForMessage:")]
string ConversationViewController (ATLConversationViewController viewController, NSObject message);
// @optional -(id)conversationViewController:(ATLConversationViewController *)viewController conversationWithParticipants:(NSSet *)participants;
[Export ("conversationViewController:conversationWithParticipants:")]
NSObject ConversationViewController (ATLConversationViewController viewController, NSSet participants);
// @optional -(id)conversationViewController:(ATLConversationViewController *)viewController willLoadWithQuery:(id)defaultQuery;
[Export ("conversationViewController:willLoadWithQuery:")]
NSObject ConversationViewController (ATLConversationViewController viewController, NSObject defaultQuery);
}
// @interface ATLConversationViewController : ATLBaseConversationViewController
[BaseType (typeof(ATLBaseConversationViewController))]
interface ATLConversationViewController
{
// +(instancetype)conversationViewControllerWithLayerClient:(id)layerClient;
[Static]
[Export ("conversationViewControllerWithLayerClient:")]
ATLConversationViewController ConversationViewControllerWithLayerClient (NSObject layerClient);
// -(instancetype)initWithLayerClient:(id)layerClient;
[Export ("initWithLayerClient:")]
IntPtr Constructor (NSObject layerClient);
// @property (nonatomic) int * layerClient;
[Export ("layerClient", ArgumentSemantic.Assign)]
unsafe int* LayerClient { get; set; }
// @property (nonatomic) int * conversation;
[Export ("conversation", ArgumentSemantic.Assign)]
unsafe int* Conversation { get; set; }
// @property (readonly, nonatomic) int * queryController;
[Export ("queryController")]
unsafe int* QueryController { get; }
[Wrap ("WeakDelegate")]
[NullAllowed]
ATLConversationViewControllerDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<ATLConversationViewControllerDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (nonatomic, weak) id<ATLConversationViewControllerDataSource> _Nullable dataSource;
[NullAllowed, Export ("dataSource", ArgumentSemantic.Weak)]
ATLConversationViewControllerDataSource DataSource { get; set; }
// -(void)registerClass:(Class<ATLMessagePresenting>)cellClass forMessageCellWithReuseIdentifier:(NSString *)reuseIdentifier;
[Export ("registerClass:forMessageCellWithReuseIdentifier:")]
void RegisterClass (ATLMessagePresenting cellClass, string reuseIdentifier);
// -(void)reloadCellForMessage:(id)message;
[Export ("reloadCellForMessage:")]
void ReloadCellForMessage (NSObject message);
// -(void)reloadCellsForMessagesSentByParticipantWithIdentifier:(NSString *)participantIdentifier;
[Export ("reloadCellsForMessagesSentByParticipantWithIdentifier:")]
void ReloadCellsForMessagesSentByParticipantWithIdentifier (string participantIdentifier);
// -(void)sendLocationMessage;
[Export ("sendLocationMessage")]
void SendLocationMessage ();
// -(void)sendMessage:(id)message;
[Export ("sendMessage:")]
void SendMessage (NSObject message);
// @property (nonatomic) NSTimeInterval dateDisplayTimeInterval;
[Export ("dateDisplayTimeInterval")]
double DateDisplayTimeInterval { get; set; }
// @property (nonatomic) BOOL marksMessagesAsRead;
[Export ("marksMessagesAsRead")]
bool MarksMessagesAsRead { get; set; }
// @property (nonatomic) BOOL shouldDisplayAvatarItemForOneOtherParticipant;
[Export ("shouldDisplayAvatarItemForOneOtherParticipant")]
bool ShouldDisplayAvatarItemForOneOtherParticipant { get; set; }
// @property (nonatomic) BOOL shouldDisplayAvatarItemForAuthenticatedUser;
[Export ("shouldDisplayAvatarItemForAuthenticatedUser")]
bool ShouldDisplayAvatarItemForAuthenticatedUser { get; set; }
// @property (nonatomic) ATLAvatarItemDisplayFrequency avatarItemDisplayFrequency;
[Export ("avatarItemDisplayFrequency", ArgumentSemantic.Assign)]
ATLAvatarItemDisplayFrequency AvatarItemDisplayFrequency { get; set; }
}
// @protocol ATLParticipantPresenting <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLParticipantPresenting
{
// @required -(void)presentParticipant:(id<ATLParticipant>)participant withSortType:(ATLParticipantPickerSortType)sortType shouldShowAvatarItem:(BOOL)shouldShowAvatarItem;
[Abstract]
[Export ("presentParticipant:withSortType:shouldShowAvatarItem:")]
void WithSortType (ATLParticipant participant, ATLParticipantPickerSortType sortType, bool shouldShowAvatarItem);
}
// @interface ATLParticipantTableViewCell : UITableViewCell <ATLParticipantPresenting>
[BaseType (typeof(UITableViewCell))]
interface ATLParticipantTableViewCell : IATLParticipantPresenting
{
// @property (nonatomic) UIFont * titleFont __attribute__((annotate("ui_appearance_selector")));
[Export ("titleFont", ArgumentSemantic.Assign)]
UIFont TitleFont { get; set; }
// @property (nonatomic) UIFont * boldTitleFont __attribute__((annotate("ui_appearance_selector")));
[Export ("boldTitleFont", ArgumentSemantic.Assign)]
UIFont BoldTitleFont { get; set; }
// @property (nonatomic) UIColor * titleColor __attribute__((annotate("ui_appearance_selector")));
[Export ("titleColor", ArgumentSemantic.Assign)]
UIColor TitleColor { get; set; }
}
// @protocol ATLParticipantTableViewControllerDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLParticipantTableViewControllerDelegate
{
// @required -(void)participantTableViewController:(ATLParticipantTableViewController *)participantTableViewController didSelectParticipant:(id<ATLParticipant>)participant;
[Abstract]
[Export ("participantTableViewController:didSelectParticipant:")]
void DidSelectParticipant (ATLParticipantTableViewController participantTableViewController, ATLParticipant participant);
// @required -(void)participantTableViewController:(ATLParticipantTableViewController *)participantTableViewController didSearchWithString:(NSString *)searchText completion:(void (^)(NSSet *))completion;
[Abstract]
[Export ("participantTableViewController:didSearchWithString:completion:")]
void DidSearchWithString (ATLParticipantTableViewController participantTableViewController, string searchText, Action<NSSet> completion);
// @optional -(void)participantTableViewController:(ATLParticipantTableViewController *)participantTableViewController didDeselectParticipant:(id<ATLParticipant>)participant;
[Export ("participantTableViewController:didDeselectParticipant:")]
void DidDeselectParticipant (ATLParticipantTableViewController participantTableViewController, ATLParticipant participant);
}
// @interface ATLParticipantTableViewController : UITableViewController
[BaseType (typeof(UITableViewController))]
interface ATLParticipantTableViewController
{
// +(instancetype)participantTableViewControllerWithParticipants:(NSSet *)participants sortType:(ATLParticipantPickerSortType)sortType;
[Static]
[Export ("participantTableViewControllerWithParticipants:sortType:")]
ATLParticipantTableViewController ParticipantTableViewControllerWithParticipants (NSSet participants, ATLParticipantPickerSortType sortType);
// @property (nonatomic) NSSet * participants;
[Export ("participants", ArgumentSemantic.Assign)]
NSSet Participants { get; set; }
// @property (nonatomic) NSSet * blockedParticipantIdentifiers;
[Export ("blockedParticipantIdentifiers", ArgumentSemantic.Assign)]
NSSet BlockedParticipantIdentifiers { get; set; }
// @property (assign, nonatomic) ATLParticipantPickerSortType sortType;
[Export ("sortType", ArgumentSemantic.Assign)]
ATLParticipantPickerSortType SortType { get; set; }
[Wrap ("WeakDelegate")]
[NullAllowed]
ATLParticipantTableViewControllerDelegate Delegate { get; set; }
// @property (nonatomic, weak) id<ATLParticipantTableViewControllerDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// @property (nonatomic) Class<ATLParticipantPresenting> cellClass;
[Export ("cellClass", ArgumentSemantic.Assign)]
ATLParticipantPresenting CellClass { get; set; }
// @property (assign, nonatomic) CGFloat rowHeight;
[Export ("rowHeight")]
nfloat RowHeight { get; set; }
// @property (assign, nonatomic) BOOL allowsMultipleSelection;
[Export ("allowsMultipleSelection")]
bool AllowsMultipleSelection { get; set; }
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern const NSInteger ATLNumberOfSectionsBeforeFirstMessageSection;
[Field ("ATLNumberOfSectionsBeforeFirstMessageSection", "__Internal")]
nint ATLNumberOfSectionsBeforeFirstMessageSection { get; }
}
// @interface ATLConversationDataSource : NSObject
[BaseType (typeof(NSObject))]
interface ATLConversationDataSource
{
// +(instancetype)dataSourceWithLayerClient:(id)layerClient query:(id)query;
[Static]
[Export ("dataSourceWithLayerClient:query:")]
ATLConversationDataSource DataSourceWithLayerClient (NSObject layerClient, NSObject query);
// @property (readonly, nonatomic) int * queryController;
[Export ("queryController")]
unsafe int* QueryController { get; }
// -(BOOL)moreMessagesAvailable;
[Export ("moreMessagesAvailable")]
[Verify (MethodToProperty)]
bool MoreMessagesAvailable { get; }
// -(void)expandPaginationWindow;
[Export ("expandPaginationWindow")]
void ExpandPaginationWindow ();
// @property (readonly, getter = isExpandingPaginationWindow, nonatomic) BOOL expandingPaginationWindow;
[Export ("expandingPaginationWindow")]
bool ExpandingPaginationWindow { [Bind ("isExpandingPaginationWindow")] get; }
// -(NSIndexPath *)queryControllerIndexPathForCollectionViewIndexPath:(NSIndexPath *)collectionViewIndexPath;
[Export ("queryControllerIndexPathForCollectionViewIndexPath:")]
NSIndexPath QueryControllerIndexPathForCollectionViewIndexPath (NSIndexPath collectionViewIndexPath);
// -(NSIndexPath *)collectionViewIndexPathForQueryControllerIndexPath:(NSIndexPath *)collectionViewIndexPath;
[Export ("collectionViewIndexPathForQueryControllerIndexPath:")]
NSIndexPath CollectionViewIndexPathForQueryControllerIndexPath (NSIndexPath collectionViewIndexPath);
// -(NSInteger)collectionViewSectionForQueryControllerRow:(NSInteger)queryControllerRow;
[Export ("collectionViewSectionForQueryControllerRow:")]
nint CollectionViewSectionForQueryControllerRow (nint queryControllerRow);
// -(id)messageAtCollectionViewIndexPath:(NSIndexPath *)collectionViewIndexPath;
[Export ("messageAtCollectionViewIndexPath:")]
NSObject MessageAtCollectionViewIndexPath (NSIndexPath collectionViewIndexPath);
// -(id)messageAtCollectionViewSection:(NSInteger)collectionViewSection;
[Export ("messageAtCollectionViewSection:")]
NSObject MessageAtCollectionViewSection (nint collectionViewSection);
}
// @interface ATLDataSourceChange : NSObject
[BaseType (typeof(NSObject))]
interface ATLDataSourceChange
{
// +(instancetype)changeObjectWithType:(id)type newIndex:(NSUInteger)newIndex currentIndex:(NSUInteger)currentIndex;
[Static]
[Export ("changeObjectWithType:newIndex:currentIndex:")]
ATLDataSourceChange ChangeObjectWithType (NSObject type, nuint newIndex, nuint currentIndex);
// @property (nonatomic) int type;
[Export ("type")]
int Type { get; set; }
// @property (nonatomic) NSInteger newIndex;
[Export ("newIndex")]
nint NewIndex { get; set; }
// @property (nonatomic) NSInteger currentIndex;
[Export ("currentIndex")]
nint CurrentIndex { get; set; }
}
// @interface ATLParticipantTableDataSet : NSObject
[BaseType (typeof(NSObject))]
interface ATLParticipantTableDataSet
{
// +(instancetype)dataSetWithParticipants:(NSSet *)participants sortType:(ATLParticipantPickerSortType)sortType;
[Static]
[Export ("dataSetWithParticipants:sortType:")]
ATLParticipantTableDataSet DataSetWithParticipants (NSSet participants, ATLParticipantPickerSortType sortType);
// @property (readonly, nonatomic) NSArray * sectionTitles;
[Export ("sectionTitles")]
[Verify (StronglyTypedNSArray)]
NSObject[] SectionTitles { get; }
// @property (readonly, nonatomic) NSUInteger numberOfSections;
[Export ("numberOfSections")]
nuint NumberOfSections { get; }
// -(NSUInteger)numberOfParticipantsInSection:(NSUInteger)section;
[Export ("numberOfParticipantsInSection:")]
nuint NumberOfParticipantsInSection (nuint section);
// -(NSIndexPath *)indexPathForParticipant:(id<ATLParticipant>)participant;
[Export ("indexPathForParticipant:")]
NSIndexPath IndexPathForParticipant (ATLParticipant participant);
// -(id<ATLParticipant>)participantAtIndexPath:(NSIndexPath *)indexPath;
[Export ("participantAtIndexPath:")]
ATLParticipant ParticipantAtIndexPath (NSIndexPath indexPath);
}
// @protocol ATLMessagePresenting <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface ATLMessagePresenting
{
// @required -(void)presentMessage:(id)message;
[Abstract]
[Export ("presentMessage:")]
void PresentMessage (NSObject message);
// @required -(void)updateWithSender:(id<ATLParticipant>)sender;
[Abstract]
[Export ("updateWithSender:")]
void UpdateWithSender (ATLParticipant sender);
// @required -(void)shouldDisplayAvatarItem:(BOOL)shouldDisplayAvatarItem;
[Abstract]
[Export ("shouldDisplayAvatarItem:")]
void ShouldDisplayAvatarItem (bool shouldDisplayAvatarItem);
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLErrorDomain;
[Field ("ATLErrorDomain", "__Internal")]
NSString ATLErrorDomain { get; }
}
// @interface ATLFirstResponder (UIResponder)
[Category]
[BaseType (typeof(UIResponder))]
interface UIResponder_ATLFirstResponder
{
// +(id)atl_currentFirstResponder;
[Static]
[Export ("atl_currentFirstResponder")]
[Verify (MethodToProperty)]
NSObject Atl_currentFirstResponder { get; }
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLMIMETypeTextPlain;
[Field ("ATLMIMETypeTextPlain", "__Internal")]
NSString ATLMIMETypeTextPlain { get; }
// extern NSString *const ATLMIMETypeImagePNG;
[Field ("ATLMIMETypeImagePNG", "__Internal")]
NSString ATLMIMETypeImagePNG { get; }
// extern NSString *const ATLMIMETypeImageJPEG;
[Field ("ATLMIMETypeImageJPEG", "__Internal")]
NSString ATLMIMETypeImageJPEG { get; }
// extern NSString *const ATLMIMETypeImageJPEGPreview;
[Field ("ATLMIMETypeImageJPEGPreview", "__Internal")]
NSString ATLMIMETypeImageJPEGPreview { get; }
// extern NSString *const ATLMIMETypeImageGIF;
[Field ("ATLMIMETypeImageGIF", "__Internal")]
NSString ATLMIMETypeImageGIF { get; }
// extern NSString *const ATLMIMETypeImageGIFPreview;
[Field ("ATLMIMETypeImageGIFPreview", "__Internal")]
NSString ATLMIMETypeImageGIFPreview { get; }
// extern NSString *const ATLMIMETypeImageSize;
[Field ("ATLMIMETypeImageSize", "__Internal")]
NSString ATLMIMETypeImageSize { get; }
// extern NSString *const ATLMIMETypeVideoQuickTime;
[Field ("ATLMIMETypeVideoQuickTime", "__Internal")]
NSString ATLMIMETypeVideoQuickTime { get; }
// extern NSString *const ATLMIMETypeLocation;
[Field ("ATLMIMETypeLocation", "__Internal")]
NSString ATLMIMETypeLocation { get; }
// extern NSString *const ATLMIMETypeDate;
[Field ("ATLMIMETypeDate", "__Internal")]
NSString ATLMIMETypeDate { get; }
// extern NSString *const ATLMIMETypeVideoMP4;
[Field ("ATLMIMETypeVideoMP4", "__Internal")]
NSString ATLMIMETypeVideoMP4 { get; }
// extern const NSUInteger ATLDefaultThumbnailSize;
[Field ("ATLDefaultThumbnailSize", "__Internal")]
nuint ATLDefaultThumbnailSize { get; }
// extern const NSUInteger ATLDefaultGIFThumbnailSize;
[Field ("ATLDefaultGIFThumbnailSize", "__Internal")]
nuint ATLDefaultGIFThumbnailSize { get; }
// extern NSString *const ATLPasteboardImageKey;
[Field ("ATLPasteboardImageKey", "__Internal")]
NSString ATLPasteboardImageKey { get; }
// extern NSString *const ATLImagePreviewWidthKey;
[Field ("ATLImagePreviewWidthKey", "__Internal")]
NSString ATLImagePreviewWidthKey { get; }
// extern NSString *const ATLImagePreviewHeightKey;
[Field ("ATLImagePreviewHeightKey", "__Internal")]
NSString ATLImagePreviewHeightKey { get; }
// extern NSString *const ATLLocationLatitudeKey;
[Field ("ATLLocationLatitudeKey", "__Internal")]
NSString ATLLocationLatitudeKey { get; }
// extern NSString *const ATLLocationLongitudeKey;
[Field ("ATLLocationLongitudeKey", "__Internal")]
NSString ATLLocationLongitudeKey { get; }
}
// @interface ATLAddressBarContainerView : UIView
[BaseType (typeof(UIView))]
interface ATLAddressBarContainerView
{
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern const CGFloat ATLAvatarImageDiameter;
[Field ("ATLAvatarImageDiameter", "__Internal")]
nfloat ATLAvatarImageDiameter { get; }
}
// @interface ATLAvatarImageView : UIImageView
[BaseType (typeof(UIImageView))]
interface ATLAvatarImageView
{
// @property (nonatomic) id<ATLAvatarItem> avatarItem;
[Export ("avatarItem", ArgumentSemantic.Assign)]
ATLAvatarItem AvatarItem { get; set; }
// @property (nonatomic) CGFloat avatarImageViewDiameter __attribute__((annotate("ui_appearance_selector")));
[Export ("avatarImageViewDiameter")]
nfloat AvatarImageViewDiameter { get; set; }
// @property (nonatomic) UIFont * initialsFont __attribute__((annotate("ui_appearance_selector")));
[Export ("initialsFont", ArgumentSemantic.Assign)]
UIFont InitialsFont { get; set; }
// @property (nonatomic) UIColor * initialsColor __attribute__((annotate("ui_appearance_selector")));
[Export ("initialsColor", ArgumentSemantic.Assign)]
UIColor InitialsColor { get; set; }
// @property (nonatomic) UIColor * imageViewBackgroundColor __attribute__((annotate("ui_appearance_selector")));
[Export ("imageViewBackgroundColor", ArgumentSemantic.Assign)]
UIColor ImageViewBackgroundColor { get; set; }
// -(void)resetView;
[Export ("resetView")]
void ResetView ();
}
// @interface ATLProgressView : UIView
[BaseType (typeof(UIView))]
interface ATLProgressView
{
// @property (readonly, nonatomic) float progress;
[Export ("progress")]
float Progress { get; }
// -(void)setProgress:(float)newProgress animated:(BOOL)animated;
[Export ("setProgress:animated:")]
void SetProgress (float newProgress, bool animated);
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern const CGFloat ATLMessageBubbleLabelVerticalPadding;
[Field ("ATLMessageBubbleLabelVerticalPadding", "__Internal")]
nfloat ATLMessageBubbleLabelVerticalPadding { get; }
// extern const CGFloat ATLMessageBubbleLabelHorizontalPadding;
[Field ("ATLMessageBubbleLabelHorizontalPadding", "__Internal")]
nfloat ATLMessageBubbleLabelHorizontalPadding { get; }
// extern const CGFloat ATLMessageBubbleLabelWidthMargin;
[Field ("ATLMessageBubbleLabelWidthMargin", "__Internal")]
nfloat ATLMessageBubbleLabelWidthMargin { get; }
// extern const CGFloat ATLMessageBubbleMapWidth;
[Field ("ATLMessageBubbleMapWidth", "__Internal")]
nfloat ATLMessageBubbleMapWidth { get; }
// extern const CGFloat ATLMessageBubbleMapHeight;
[Field ("ATLMessageBubbleMapHeight", "__Internal")]
nfloat ATLMessageBubbleMapHeight { get; }
// extern const CGFloat ATLMessageBubbleDefaultHeight;
[Field ("ATLMessageBubbleDefaultHeight", "__Internal")]
nfloat ATLMessageBubbleDefaultHeight { get; }
// extern NSString *const ATLUserDidTapLinkNotification;
[Field ("ATLUserDidTapLinkNotification", "__Internal")]
NSString ATLUserDidTapLinkNotification { get; }
// extern NSString *const ATLUserDidTapPhoneNumberNotification;
[Field ("ATLUserDidTapPhoneNumberNotification", "__Internal")]
NSString ATLUserDidTapPhoneNumberNotification { get; }
}
// @interface ATLMessageBubbleView : UIView <UIAppearanceContainer>
[BaseType (typeof(UIView))]
interface ATLMessageBubbleView : IUIAppearanceContainer
{
// -(void)updateWithAttributedText:(NSAttributedString *)text;
[Export ("updateWithAttributedText:")]
void UpdateWithAttributedText (NSAttributedString text);
// -(void)updateWithImage:(UIImage *)image width:(CGFloat)width;
[Export ("updateWithImage:width:")]
void UpdateWithImage (UIImage image, nfloat width);
// -(void)updateWithVideoThumbnail:(UIImage *)image width:(CGFloat)width;
[Export ("updateWithVideoThumbnail:width:")]
void UpdateWithVideoThumbnail (UIImage image, nfloat width);
// -(void)updateWithLocation:(CLLocationCoordinate2D)location;
[Export ("updateWithLocation:")]
void UpdateWithLocation (CLLocationCoordinate2D location);
// -(void)prepareForReuse;
[Export ("prepareForReuse")]
void PrepareForReuse ();
// -(void)updateProgressIndicatorWithProgress:(float)progress visible:(BOOL)visible animated:(BOOL)animated;
[Export ("updateProgressIndicatorWithProgress:visible:animated:")]
void UpdateProgressIndicatorWithProgress (float progress, bool visible, bool animated);
// @property (nonatomic) UILabel * bubbleViewLabel;
[Export ("bubbleViewLabel", ArgumentSemantic.Assign)]
UILabel BubbleViewLabel { get; set; }
// @property (nonatomic) UIImageView * bubbleImageView;
[Export ("bubbleImageView", ArgumentSemantic.Assign)]
UIImageView BubbleImageView { get; set; }
// @property (nonatomic) NSTextCheckingType textCheckingTypes;
[Export ("textCheckingTypes", ArgumentSemantic.Assign)]
NSTextCheckingType TextCheckingTypes { get; set; }
// @property (nonatomic) NSArray * menuControllerActions;
[Export ("menuControllerActions", ArgumentSemantic.Assign)]
[Verify (StronglyTypedNSArray)]
NSObject[] MenuControllerActions { get; set; }
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern const CGFloat ATLMessageCellHorizontalMargin;
[Field ("ATLMessageCellHorizontalMargin", "__Internal")]
nfloat ATLMessageCellHorizontalMargin { get; }
}
// @interface ATLBaseCollectionViewCell : UICollectionViewCell <ATLMessagePresenting>
[BaseType (typeof(UICollectionViewCell))]
interface ATLBaseCollectionViewCell : IATLMessagePresenting
{
// @property (nonatomic) UIColor * bubbleViewColor __attribute__((annotate("ui_appearance_selector")));
[Export ("bubbleViewColor", ArgumentSemantic.Assign)]
UIColor BubbleViewColor { get; set; }
// @property (nonatomic) CGFloat bubbleViewCornerRadius __attribute__((annotate("ui_appearance_selector")));
[Export ("bubbleViewCornerRadius")]
nfloat BubbleViewCornerRadius { get; set; }
// @property (nonatomic) ATLMessageBubbleView * bubbleView;
[Export ("bubbleView", ArgumentSemantic.Assign)]
ATLMessageBubbleView BubbleView { get; set; }
// @property (nonatomic) ATLAvatarImageView * avatarImageView;
[Export ("avatarImageView", ArgumentSemantic.Assign)]
ATLAvatarImageView AvatarImageView { get; set; }
// @property (nonatomic) int * message;
[Export ("message", ArgumentSemantic.Assign)]
unsafe int* Message { get; set; }
// -(void)updateBubbleWidth:(CGFloat)bubbleWidth;
[Export ("updateBubbleWidth:")]
void UpdateBubbleWidth (nfloat bubbleWidth);
// -(void)configureCellForType:(ATLCellType)cellType;
[Export ("configureCellForType:")]
void ConfigureCellForType (ATLCellType cellType);
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLGIFAccessibilityLabel;
[Field ("ATLGIFAccessibilityLabel", "__Internal")]
NSString ATLGIFAccessibilityLabel { get; }
// extern NSString *const ATLImageAccessibilityLabel;
[Field ("ATLImageAccessibilityLabel", "__Internal")]
NSString ATLImageAccessibilityLabel { get; }
// extern NSString *const ATLVideoAccessibilityLabel;
[Field ("ATLVideoAccessibilityLabel", "__Internal")]
NSString ATLVideoAccessibilityLabel { get; }
}
// @interface ATLMessageCollectionViewCell : ATLBaseCollectionViewCell
[BaseType (typeof(ATLBaseCollectionViewCell))]
interface ATLMessageCollectionViewCell
{
// @property (nonatomic) UIFont * messageTextFont __attribute__((annotate("ui_appearance_selector")));
[Export ("messageTextFont", ArgumentSemantic.Assign)]
UIFont MessageTextFont { get; set; }
// @property (nonatomic) UIColor * messageTextColor __attribute__((annotate("ui_appearance_selector")));
[Export ("messageTextColor", ArgumentSemantic.Assign)]
UIColor MessageTextColor { get; set; }
// @property (nonatomic) UIColor * messageLinkTextColor __attribute__((annotate("ui_appearance_selector")));
[Export ("messageLinkTextColor", ArgumentSemantic.Assign)]
UIColor MessageLinkTextColor { get; set; }
// @property (nonatomic) NSTextCheckingType messageTextCheckingTypes __attribute__((annotate("ui_appearance_selector")));
[Export ("messageTextCheckingTypes", ArgumentSemantic.Assign)]
NSTextCheckingType MessageTextCheckingTypes { get; set; }
// +(CGFloat)cellHeightForMessage:(id)message inView:(UIView *)view;
[Static]
[Export ("cellHeightForMessage:inView:")]
nfloat CellHeightForMessage (NSObject message, UIView view);
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLOutgoingMessageCellIdentifier;
[Field ("ATLOutgoingMessageCellIdentifier", "__Internal")]
NSString ATLOutgoingMessageCellIdentifier { get; }
}
// @interface ATLOutgoingMessageCollectionViewCell : ATLMessageCollectionViewCell
[BaseType (typeof(ATLMessageCollectionViewCell))]
interface ATLOutgoingMessageCollectionViewCell
{
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLIncomingMessageCellIdentifier;
[Field ("ATLIncomingMessageCellIdentifier", "__Internal")]
NSString ATLIncomingMessageCellIdentifier { get; }
}
// @interface ATLIncomingMessageCollectionViewCell : ATLMessageCollectionViewCell
[BaseType (typeof(ATLMessageCollectionViewCell))]
interface ATLIncomingMessageCollectionViewCell
{
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLMoreMessagesHeaderIdentifier;
[Field ("ATLMoreMessagesHeaderIdentifier", "__Internal")]
NSString ATLMoreMessagesHeaderIdentifier { get; }
}
// @interface ATLConversationCollectionViewMoreMessagesHeader : UICollectionReusableView
[BaseType (typeof(UICollectionReusableView))]
interface ATLConversationCollectionViewMoreMessagesHeader
{
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLConversationViewHeaderIdentifier;
[Field ("ATLConversationViewHeaderIdentifier", "__Internal")]
NSString ATLConversationViewHeaderIdentifier { get; }
}
// @interface ATLConversationCollectionViewHeader : UICollectionReusableView
[BaseType (typeof(UICollectionReusableView))]
interface ATLConversationCollectionViewHeader
{
// @property (nonatomic) LYRMessage * message;
[Export ("message", ArgumentSemantic.Assign)]
LYRMessage Message { get; set; }
// @property (nonatomic) UIFont * participantLabelFont __attribute__((annotate("ui_appearance_selector")));
[Export ("participantLabelFont", ArgumentSemantic.Assign)]
UIFont ParticipantLabelFont { get; set; }
// @property (nonatomic) UIColor * participantLabelTextColor __attribute__((annotate("ui_appearance_selector")));
[Export ("participantLabelTextColor", ArgumentSemantic.Assign)]
UIColor ParticipantLabelTextColor { get; set; }
// -(void)updateWithParticipantName:(NSString *)participantName;
[Export ("updateWithParticipantName:")]
void UpdateWithParticipantName (string participantName);
// -(void)updateWithAttributedStringForDate:(NSAttributedString *)date;
[Export ("updateWithAttributedStringForDate:")]
void UpdateWithAttributedStringForDate (NSAttributedString date);
// +(CGFloat)headerHeightWithDateString:(NSAttributedString *)dateString participantName:(NSString *)participantName inView:(UIView *)view;
[Static]
[Export ("headerHeightWithDateString:participantName:inView:")]
nfloat HeaderHeightWithDateString (NSAttributedString dateString, string participantName, UIView view);
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLConversationViewFooterIdentifier;
[Field ("ATLConversationViewFooterIdentifier", "__Internal")]
NSString ATLConversationViewFooterIdentifier { get; }
}
// @interface ATLConversationCollectionViewFooter : UICollectionReusableView
[BaseType (typeof(UICollectionReusableView))]
interface ATLConversationCollectionViewFooter
{
// @property (nonatomic) LYRMessage * message;
[Export ("message", ArgumentSemantic.Assign)]
LYRMessage Message { get; set; }
// -(void)updateWithAttributedStringForRecipientStatus:(NSAttributedString *)recipientStatus;
[Export ("updateWithAttributedStringForRecipientStatus:")]
void UpdateWithAttributedStringForRecipientStatus (NSAttributedString recipientStatus);
// +(CGFloat)footerHeightWithRecipientStatus:(NSAttributedString *)recipientStatus clustered:(BOOL)clustered;
[Static]
[Export ("footerHeightWithRecipientStatus:clustered:")]
nfloat FooterHeightWithRecipientStatus (NSAttributedString recipientStatus, bool clustered);
}
// @interface ATLConversationCollectionView : UICollectionView
[BaseType (typeof(UICollectionView))]
interface ATLConversationCollectionView
{
}
// @interface ATLConversationView : UIView
[BaseType (typeof(UIView))]
interface ATLConversationView
{
// @property (nonatomic) UIView * inputAccessoryView;
[Export ("inputAccessoryView", ArgumentSemantic.Assign)]
UIView InputAccessoryView { get; set; }
}
// @interface ATLParticipantSectionHeaderView : UITableViewHeaderFooterView
[BaseType (typeof(UITableViewHeaderFooterView))]
interface ATLParticipantSectionHeaderView
{
// @property (nonatomic) UILabel * sectionHeaderLabel;
[Export ("sectionHeaderLabel", ArgumentSemantic.Assign)]
UILabel SectionHeaderLabel { get; set; }
// @property (nonatomic) UIFont * sectionHeaderFont __attribute__((annotate("ui_appearance_selector")));
[Export ("sectionHeaderFont", ArgumentSemantic.Assign)]
UIFont SectionHeaderFont { get; set; }
// @property (nonatomic) UIColor * sectionHeaderTextColor __attribute__((annotate("ui_appearance_selector")));
[Export ("sectionHeaderTextColor", ArgumentSemantic.Assign)]
UIColor SectionHeaderTextColor { get; set; }
// @property (nonatomic) UIColor * sectionHeaderBackgroundColor __attribute__((annotate("ui_appearance_selector")));
[Export ("sectionHeaderBackgroundColor", ArgumentSemantic.Assign)]
UIColor SectionHeaderBackgroundColor { get; set; }
}
[Static]
[Verify (ConstantsInterfaceAssociation)]
partial interface Constants
{
// extern NSString *const ATLVersionString;
[Field ("ATLVersionString", "__Internal")]
NSString ATLVersionString { get; }
}
|
using System;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.IO;
using Xamarin.Forms;
namespace Tianhai.OujiangApp.Schedule.ViewModels{
public class LoginViewModel:BaseViewModel{
public LoginViewModel(View PageContent,INavigation Navigation,Page Page){
Title="登入";
LoginCommand=new Command(async ()=>{
string username=PageContent.FindByName<Entry>("username").Text;
string password=PageContent.FindByName<Entry>("password").Text;
string captcha=PageContent.FindByName<Entry>("captcha").Text;
if(String.IsNullOrWhiteSpace(username)||String.IsNullOrWhiteSpace(password)||String.IsNullOrWhiteSpace(captcha)){
lblHintVisible=true;
lblHintText="请完整填写所有内容";
return;
}
bool r=await Login(username.Trim(),password.Trim(),captcha.Trim());
if(r){
SaveCredential(PageContent);
await Page.DisplayAlert("登入成功","你现在可以去更新课表了。","好的");
await Navigation.PopAsync();
}else{
await LoadCaptcha();
}
return;
});
ReloadCaptchaCommand=new Command(async ()=>{
lblHintVisible=false;
await LoadCaptcha();
});
}
public void LoadSavedCredential(View PageContent){
var savedCredential=App.PreferenceDatabase.GetOACredential();
if(savedCredential==null){
return;
}
PageContent.FindByName<Entry>("username").Text=savedCredential.Username;
PageContent.FindByName<Entry>("password").Text=savedCredential.Password;
}
public void SaveCredential(View PageContent){
var savedCredential=new Models.Preferences.OACredential{
Username=PageContent.FindByName<Entry>("username").Text,
Password=PageContent.FindByName<Entry>("password").Text
};
App.PreferenceDatabase.SetOACredential(savedCredential);
}
public async Task LoadCaptcha(){
btnReloadCaptchaIsEnabled=false;
btnReloadCaptchaText="正在加载验证码";
try{
string captchaDataurl=await Services.UserService.loginStartWithCaptcha();
var captchaBase64=Regex.Match(captchaDataurl, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var captchaBinary=Convert.FromBase64String(captchaBase64);
imgCaptcha=ImageSource.FromStream(()=>new MemoryStream(captchaBinary));
}catch(Exception e){
lblHintText=String.Format("验证码加载失败,可能是网络状况不佳。{0}",e.Message);
lblHintVisible=true;
}
btnReloadCaptchaIsEnabled=true;
btnReloadCaptchaText="刷新验证码";
}
public async Task<bool> Login(string username,string password,string captcha){
btnLoginIsEnabled=false;
lblHintVisible=false;
actidctIsRunning=true;
bool result=false;
try{
result=await Services.UserService.loginSubmit(username,password,captcha);
if(!result){
lblHintText="用户名/密码或验证码出错,请检查。";
lblHintVisible=true;
}else{
lblHintText="登入成功";
//lblHintVisible=true;
}
}catch(Exceptions.SessionTimeoutException){
lblHintText="验证码过期,请刷新。";
lblHintVisible=true;
}catch(Exception e){
lblHintText=String.Format("遇到未知错误,可能是网络状况不佳。{0}",e.Message);
lblHintVisible=true;
}
actidctIsRunning=false;
btnLoginIsEnabled=true;
return result;
}
public ICommand LoginCommand{get;}
public ICommand ReloadCaptchaCommand{get;}
private bool _btnLoginIsEnabled=true;
public bool btnLoginIsEnabled{
get{
return _btnLoginIsEnabled;
}
set{
_btnLoginIsEnabled=value;
OnPropertyChanged();
}
}
private bool _btnReloadCaptchaIsEnabled=true;
public bool btnReloadCaptchaIsEnabled{
get{
return _btnReloadCaptchaIsEnabled;
}
set{
_btnReloadCaptchaIsEnabled=value;
OnPropertyChanged();
}
}
private string _btnReloadCaptchaText="刷新验证码";
public string btnReloadCaptchaText{
get{
return _btnReloadCaptchaText;
}
set{
_btnReloadCaptchaText=value;
OnPropertyChanged();
}
}
private bool _lblHintVisible=false;
private string _lblHintText="";
public bool lblHintVisible{
get{
return _lblHintVisible;
}
set{
_lblHintVisible=value;
OnPropertyChanged();
}
}
public string lblHintText{
get{
return _lblHintText;
}
set{
_lblHintText=value;
OnPropertyChanged();
}
}
private bool _actidctIsRunning=false;
public bool actidctIsRunning{
get{
return _actidctIsRunning;
}
set{
_actidctIsRunning=value;
OnPropertyChanged();
}
}
private ImageSource _imgCaptcha;
public ImageSource imgCaptcha{
get{
return _imgCaptcha;
}
set{
_imgCaptcha=value;
OnPropertyChanged();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace Rss2Email
{
class Program
{
//Arguments - RSS source, update period in minutes, list of e-mails
static void Main(string[] args)
{
int updatePeriod = int.Parse(args[1]);
RssFeed feed = new RssFeed(new Uri(args[0]), TimeSpan.FromMinutes(updatePeriod));
string[] subscribers = new string[args.Length - 2];
Array.Copy(args, 2, subscribers, 0, subscribers.Length);
feed.Subscribe(subscribers);
feed.StartChecking();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
public class JsonObject
{
public string ToJSON()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(this);
}
}
public class NewTaskHtml : JsonObject
{
public string StoryRowID { get; set; }
public string RowHtml { get; set; }
}
public class UpdateTaskValues : JsonObject
{
public string StatusHtml { get; set; }
public string AssignedTo { get; set; }
public string ShortDescription { get; set; }
public string Hours { get; set; }
}
public class UpdateIncidentValues : JsonObject
{
public string StatusHtml { get; set; }
public string AssignedTo { get; set; }
public string ShortDescription { get; set; }
}
public class UpdateStoryValues : JsonObject
{
public string StatusHtml { get; set; }
public string AssignedTo { get; set; }
public string ExpenseType { get; set; }
public string ShortDescription { get; set; }
public string Blocked { get; set; }
public string BlockedReason { get; set; }
}
|
using System;
using System.Collections.Generic;
using Alabo.Data.People.Users.Domain.Services;
using Alabo.Domains.Entities;
using Alabo.Domains.Query;
using Alabo.Extensions;
using Alabo.Framework.Core.WebApis;
using Alabo.Framework.Core.WebUis;
using Alabo.Industry.Cms.Articles.Domain.Entities;
using Alabo.Industry.Cms.Articles.Domain.Services;
using Alabo.UI;
using Alabo.UI.Design.AutoLists;
using MongoDB.Bson;
namespace Alabo.Industry.Cms.Articles.UI.AutoForm
{
public class ArticleHelpAutoList : UIBase, IAutoList
{
public PageResult<AutoListItem> PageList(object query, AutoBaseModel autoModel)
{
var dic = query.ToObject<Dictionary<string, string>>();
dic.TryGetValue("loginUserId", out var userId);
dic.TryGetValue("pageIndex", out var pageIndexStr);
var pageIndex = pageIndexStr.ToInt64();
if (pageIndex <= 0) {
pageIndex = 1;
}
var temp = new ExpressionQuery<Article>
{
EnablePaging = true,
PageIndex = (int) pageIndex,
PageSize = 15
};
temp.And(e => e.ChannelId == ObjectId.Parse("e02220001110000000000003"));
var model = Resolve<IArticleService>().GetPagedList(temp);
var users = Resolve<IUserDetailService>().GetList();
var list = new List<AutoListItem>();
foreach (var item in model)
{
var apiData = new AutoListItem
{
Title = item.Title,
Intro = item.Intro,
Value = item.Author,
Image = "http://s-test.qiniuniu99.com" + item.ImageUrl,
Id = item.Id,
Url = $"/pages/index?path=articles_help_view&id={item.Id}"
};
list.Add(apiData);
}
return ToPageList(list, model);
}
public Type SearchType()
{
throw new NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.OleDb;
using Novacode;
using System.IO;
using System.Data.Common;
namespace Aviso
{
public partial class MainForm : Form
{
//Вычислить следующий номер авизо
public string CalcPostAvisoNextNum(DataTable tbl)
{
int max = 0;
foreach (DataRow row in tbl.Rows)
{
if (max < Convert.ToInt32(row["NUM"]))
max = Convert.ToInt32(row["NUM"]);
}
max++;
return max.ToString("000");
}
//Редактирование почтового авизо
private void EditPostAviso()
{
AvisoPostEdit frm = new AvisoPostEdit(this.postavisoBindingSource);
if (frm.ShowDialog() == DialogResult.OK)
postavisoBindingSource.EndEdit();
else
postavisoBindingSource.CancelEdit();
this.post_avisoTableAdapter.Update(this.avisoDataSet);
dgvAvisoPost.Refresh();
}
//Редактирование телеграфного авизо
private void EditTeleAviso()
{
AvisoTeleEdit frm = new AvisoTeleEdit(this.telegraphavisoBindingSource);
if (frm.ShowDialog() == DialogResult.OK)
telegraphavisoBindingSource.EndEdit();
else
telegraphavisoBindingSource.CancelEdit();
this.telegraph_avisoTableAdapter.Update(this.avisoDataSet);
dgvAvisoTele.Refresh();
}
public MainForm()
{
InitializeComponent();
//this.dgvLookup.DataSource = lookupDataSet;
//this.dgvLookup.DataMember = lookupDataSet.Tables[0].TableName;
//dgvLookup.DataSource = LookupList.lookupBs;
}
private void bindingSource1_CurrentChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'avisoDataSet.telegraph_aviso' table. You can move, or remove it, as needed.
this.telegraph_avisoTableAdapter.Fill(this.avisoDataSet.telegraph_aviso);
// TODO: This line of code loads data into the 'avisoDataSet.post_aviso' table. You can move, or remove it, as needed.
this.post_avisoTableAdapter.Fill(this.avisoDataSet.post_aviso);
}
private void button4_Click(object sender, EventArgs e)
{
}
private void mAdd_Click(object sender, EventArgs e)
{
if (tcMain.SelectedTab == tpPostAviso)
{
DataRowView row = (DataRowView)postavisoBindingSource.AddNew();
row["NUM"] = CalcPostAvisoNextNum(avisoDataSet.Tables["post_aviso"]);
row["CREATE_DATE"] = DateTime.Today;
row["KPD_DATE"] = DateTime.Today;
EditPostAviso();
}
else if (tcMain.SelectedTab == tpTeleAviso)
{
DataRowView row = (DataRowView)telegraphavisoBindingSource.AddNew();
row["NUM"] = CalcPostAvisoNextNum(avisoDataSet.Tables["telegraph_aviso"]);
row["CREATE_DATE"] = DateTime.Today;
row["KPD_DATE"] = DateTime.Today;
EditTeleAviso();
}
}
private void mEdit_Click(object sender, EventArgs e)
{
if (tcMain.SelectedTab == tpPostAviso)
{
EditPostAviso();
}
else if (tcMain.SelectedTab == tpTeleAviso)
{
EditTeleAviso();
}
}
private void mDel_Click(object sender, EventArgs e)
{
BindingSource bs;
if (tcMain.SelectedTab == tpPostAviso)
bs = postavisoBindingSource;
else if (tcMain.SelectedTab == tpTeleAviso)
bs = telegraphavisoBindingSource;
else
return;
if (bs.Count > 0)
{
if (MessageBox.Show("Вы уверены что хотите удалить выделенное авизо?",
"Подтверждение удаления авизо",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
bs.RemoveCurrent();
bs.EndEdit();
if (tcMain.SelectedTab == tpPostAviso)
post_avisoTableAdapter.Update(avisoDataSet);
else if (tcMain.SelectedTab == tpTeleAviso)
telegraph_avisoTableAdapter.Update(avisoDataSet);
}
}
}
private void mPrint_Click(object sender, EventArgs e)
{
AvisoReporter rep;
BindingSource bs;
if (dlgSelectReport.ShowDialog()== DialogResult.OK && dlgSelectReport.FileName != "")
{
if (tcMain.SelectedTab == tpPostAviso)
{
rep = new AvisoPostReporter();
bs = postavisoBindingSource;
}
else if (tcMain.SelectedTab == tpTeleAviso)
{
rep = new AvisoTelegraphReporter();
bs = telegraphavisoBindingSource;
}
else
return;
if (rep.PrintCurrent(bs, dlgSelectReport.FileName))
MessageBox.Show("Отчет успешно сформирован", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("Не удалось сформировать отчет", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
using System;
using Uintra.Infrastructure.TypeProviders;
namespace Uintra.Features.Permissions.TypeProviders
{
public class PermissionActivityTypeProvider : EnumTypeProviderBase, IPermissionResourceTypeProvider
{
public PermissionActivityTypeProvider(params Type[] enums) : base(enums)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using Docller.Core.Repository.Mappers;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace Docller.Core.Repository.Accessors
{
public class StoredProcAccessor<TResult>:SprocAccessor<TResult> where TResult : new()
{
readonly IParameterMapper _parameterMapper;
readonly string _procedureName;
private IResultSetMapper<TResult> _resultSetMapper;
public StoredProcAccessor(Database database, string procedureName, IParameterMapper parameterMapper)
: base(database, procedureName, parameterMapper, MapBuilder<TResult>.MapAllProperties().Build())
{
_parameterMapper = parameterMapper;
_procedureName = procedureName;
_resultSetMapper = new GenericResultSetMapper<TResult>(MapBuilder<TResult>.MapAllProperties().Build());
}
/// <summary>
/// Creates a new instance of <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.SprocAccessor`1"/> that works for a specific <paramref name="database"/>
/// and uses <paramref name="rowMapper"/> to convert the returned rows to clr type <typeparamref name="TResult"/>.
/// </summary>
/// <param name="database">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.Database"/> used to execute the Transact-SQL.</param>
/// <param name="procedureName">The stored procedure that will be executed.</param>
/// <param name="rowMapper">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.IRowMapper`1"/> that will be used to convert the returned data to clr type <typeparamref name="TResult"/>.</param>
/// <param name="parameterMapper">The parameter mapper.</param>
public StoredProcAccessor(Database database, string procedureName, IRowMapper<TResult> rowMapper, IParameterMapper parameterMapper) : base(database, procedureName, rowMapper)
{
_parameterMapper = parameterMapper;
_procedureName = procedureName;
_resultSetMapper = new GenericResultSetMapper<TResult>(rowMapper);
}
/// <summary>
/// Creates a new instance of <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.SprocAccessor`1"/> that works for a specific <paramref name="database"/>
/// and uses <paramref name="resultSetMapper"/> to convert the returned set to an enumerable of clr type <typeparamref name="TResult"/>.
/// </summary>
/// <param name="database">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.Database"/> used to execute the Transact-SQL.</param>
/// <param name="procedureName">The stored procedure that will be executed.</param>
/// <param name="resultSetMapper">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.IResultSetMapper`1"/> that will be used to convert the returned set to an enumerable of clr type <typeparamref name="TResult"/>.</param>
/// <param name="parameterMapper">The parameter mapper.</param>
public StoredProcAccessor(Database database, string procedureName, IResultSetMapper<TResult> resultSetMapper, IParameterMapper parameterMapper) : base(database, procedureName, resultSetMapper)
{
_parameterMapper = parameterMapper;
_procedureName = procedureName;
_resultSetMapper = resultSetMapper;
}
/// <summary>
/// Creates a new instance of <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.SprocAccessor`1"/> that works for a specific <paramref name="database"/>
/// and uses <paramref name="rowMapper"/> to convert the returned rows to clr type <typeparamref name="TResult"/>.
/// The <paramref name="parameterMapper"/> will be used to interpret the parameters passed to the Execute method.
/// </summary>
/// <param name="database">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.Database"/> used to execute the Transact-SQL.</param><param name="procedureName">The stored procedure that will be executed.</param><param name="parameterMapper">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.IParameterMapper"/> that will be used to interpret the parameters passed to the Execute method.</param><param name="rowMapper">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.IRowMapper`1"/> that will be used to convert the returned data to clr type <typeparamref name="TResult"/>.</param>
public StoredProcAccessor(Database database, string procedureName, IParameterMapper parameterMapper, IRowMapper<TResult> rowMapper) : base(database, procedureName, parameterMapper, rowMapper)
{
_parameterMapper = parameterMapper;
_procedureName = procedureName;
_resultSetMapper = new GenericResultSetMapper<TResult>(rowMapper);
}
/// <summary>
/// Creates a new instance of <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.SprocAccessor`1"/> that works for a specific <paramref name="database"/>
/// and uses <paramref name="resultSetMapper"/> to convert the returned set to an enumerable of clr type <typeparamref name="TResult"/>.
/// The <paramref name="parameterMapper"/> will be used to interpret the parameters passed to the Execute method.
/// </summary>
/// <param name="database">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.Database"/> used to execute the Transact-SQL.</param><param name="procedureName">The stored procedure that will be executed.</param><param name="parameterMapper">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.IParameterMapper"/> that will be used to interpret the parameters passed to the Execute method.</param><param name="resultSetMapper">The <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.IResultSetMapper`1"/> that will be used to convert the returned set to an enumerable of clr type <typeparamref name="TResult"/>.</param>
public StoredProcAccessor(Database database, string procedureName, IParameterMapper parameterMapper, IResultSetMapper<TResult> resultSetMapper)
: base(database, procedureName, parameterMapper, resultSetMapper)
{
_parameterMapper = parameterMapper;
_procedureName = procedureName;
_resultSetMapper = resultSetMapper;
}
/// <summary>
/// Executes the non query.
/// </summary>
/// <param name="parameterValues">The parameter values.</param>
/// <returns></returns>
public int ExecuteNonQuery(params object[] parameterValues)
{
int val;
using (DbCommand command = Database.GetStoredProcCommand(_procedureName))
{
_parameterMapper.AssignParameters(command, parameterValues);
val = Database.ExecuteNonQuery(command);
}
if (this._parameterMapper is IOutputParameterMapper)
{
((IOutputParameterMapper)this._parameterMapper).AssignOutpurParameters();
}
return val;
}
public IEnumerable<TResult> Execute(DbTransaction transaction, params object[] parameterValues)
{
IEnumerable<TResult> results;
using (DbCommand command = Database.GetStoredProcCommand(_procedureName))
{
_parameterMapper.AssignParameters(command, parameterValues);
IDataReader reader = Database.ExecuteReader(command,transaction);
results = this._resultSetMapper.MapSet(reader);
}
return results;
}
/// <summary>
/// Executes the reader.
/// </summary>
/// <param name="parameterValues">The parameter values.</param>
/// <returns></returns>
public override IEnumerable<TResult> Execute(params object[] parameterValues)
{
IEnumerable<TResult> results;
using (DbCommand command = Database.GetStoredProcCommand(_procedureName))
{
_parameterMapper.AssignParameters(command, parameterValues);
IDataReader reader = Database.ExecuteReader(command);
results = this._resultSetMapper.MapSet(reader);
}
return results;
}
public TResult ExecuteSingle(params object[] paramterValues)
{
IEnumerable<TResult> results = this.Execute(paramterValues);
return results != null ? results.FirstOrDefault() : default(TResult);
}
public TResult ExecuteSingle(DbTransaction dbTransaction, params object[] paramterValues)
{
IEnumerable<TResult> results = this.Execute(dbTransaction, paramterValues);
return results != null ? results.FirstOrDefault() : default(TResult);
}
}
}
|
using FamousQuoteQuiz.Data.ServiceModels.Enums;
using System.Threading.Tasks;
namespace FamousQuoteQuiz.Data.ServiceContracts
{
public interface IQuoteService
{
Task CreateQuote(Data.ServiceModels.Quote quoteModel);
Task EditQuote(Data.ServiceModels.Quote quoteModel);
Task DeleteQuote(Data.ServiceModels.Quote quoteModel);
ServiceModels.Quote[] GetQuotes(int currentPage, int pageSize, QuoteMode? mode);
}
}
|
using ApiSGCOlimpiada.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSGCOlimpiada.Data.TipoCompraDAO
{
public interface ITipoCompraDAO
{
IEnumerable<TipoCompra> GetAll();
List<TipoCompra> FindBySearch(string search);
TipoCompra Find(long id);
bool Add(TipoCompra grupo);
bool Update(TipoCompra grupo, long id);
bool Remove(long id);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnPowerup : MonoBehaviour
{
public GameObject powerupPrefab;
private GameObject _currentPowerup;
public float SpawnTime;
public Transform spawnLocation;
public bool Spawning;
private float _timer;
// Start is called before the first frame update
void Start()
{
Spawning = true;
}
// Update is called once per frame
void Update()
{
if (Spawning)
{
_timer -= Time.deltaTime;
if (_timer <= 0)
{
Spawning = false;
_currentPowerup = Instantiate(powerupPrefab, transform.position, Quaternion.identity);
_currentPowerup.GetComponent<PowerupScript>()._spawner = this;
_timer = SpawnTime;
}
}
}
}
|
#region License
// Copyright (c) 2012 Trafficspaces Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Reference Documentation: http://support.trafficspaces.com/kb/api/api-introduction
#endregion
using Trafficspaces.Api.Model;
using Trafficspaces.Api.Controller;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Trafficspaces.Api.Tests {
public abstract class ApiTest : IApiTest {
public ConnectorFactory factory { get; set; }
public Dictionary<string, string> defaults { get; set; }
protected ApiTest(ConnectorFactory factory, Dictionary<string, string> defaults) {
this.factory = factory;
this.defaults = defaults;
}
public virtual void run<T>() where T : Resource, new() {
System.Console.WriteLine("\n------ START: " + GetType().Name);
runTest<T>("List");
T resource = (T) runTest<T>("Create");
if (resource != null) {
object[] args = new object[] { resource.id };
runTest<T>("Update", args);
runTest<T>("Process", args);
runTest<T>("Delete", args);
}
System.Console.WriteLine("------ FINISH: " + GetType().Name + "\n");
}
public virtual List<T> List<T>() where T : Resource, new() { throw new NotImplementedException(); }
public virtual T Create<T>() where T : Resource, new() { throw new NotImplementedException(); }
public virtual bool Update<T>(string id) where T : Resource, new() { throw new NotImplementedException(); }
public virtual bool Process<T>(string id) where T : Resource, new() { throw new NotImplementedException(); }
public virtual bool Delete<T>(string id) { throw new NotImplementedException(); }
private object runTest<T>(string testName, object[] args = null) {
var thisType = GetType();
var method = thisType.GetMethod(testName);
object result = default(T);
// If the subclass has implemented the test method, invoke it
if (method.DeclaringType == thisType && !method.IsAbstract) {
method = method.MakeGenericMethod(typeof(T));
onTestStart<T>(testName);
try {
result = method.Invoke(this, args);
onTestComplete<T>(testName, result);
} catch (Exception e) {
onTestComplete<T>(testName, e);
result = default(T);
}
}
return result;
}
public void onTestStart<T>(string testName) { }
public void onTestComplete<T>(string testName, object result) {
bool testPassed = false;
string message = null;
if (result != null) {
var type = result.GetType();
if (type == typeof(bool)) {
testPassed = (bool)result;
} if (type.IsSubclassOf(typeof(Exception))) {
testPassed = false;
message = ((Exception)result).GetBaseException().Message;
} else {
testPassed = result != null;
if (type == typeof(List<T>)) {
message = "Found " + ((List<T>)result).Count() + " resources";
} else {
message = result.ToString();
}
}
}
System.Console.WriteLine(GetType().Name + ": " + testName + ": " + (testPassed ? "Success" : "Failed") + (message != null ? (": " + message) : ""));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LD4CollisionAI : MonoBehaviour {
public GameObject mainAIRef;
int nbWrongAI;
bool mainAIHere;
public bool douglasIsolated;
private void OnTriggerEnter(Collider other)
{
if(other.tag == "AI")
{
if(other.gameObject != mainAIRef)
{
nbWrongAI++;
}
else
{
mainAIHere = true;
}
}
CheckCondition();
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "AI")
{
if (other.gameObject != mainAIRef)
{
nbWrongAI--;
}
else
{
mainAIHere = false;
}
}
CheckCondition();
}
void CheckCondition()
{
print(nbWrongAI);
print(mainAIHere);
if(nbWrongAI<=0 && mainAIHere)
{
douglasIsolated = true;
}
else
{
douglasIsolated = false;
}
}
}
|
using Discord;
using OrbCore.ContentStructures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrbCore.Interfaces.Receivers {
public interface IGuildTextMessageReceiver {
Task OnGuildTextMessageReceived(GuildTextMessageContent message);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisPSR
{
class Department : IData
{
public Department( string province, string type)
{
City = province;
Type = type;
}
public string City { get; set; }
public string Type { get; set; } //komenda miejska, powiatowa, wojewódzka
public void GetInfo()
{
Console.WriteLine($"Komenda {Type}, miasto {City}.");
}
}
}
|
using System;
using System.Collections.Generic;
using ContactListSample.Models;
using ContactListSample.Services;
using ContactListSample.ViewModels;
using Xamarin.Forms;
namespace ContactListSample.Views
{
public partial class EditNumberPage : ContentPage
{
IContactService _contactService;
public int NbrContactEdit;
public EditNumberPage(List<Contact> SelectedEdit, IContactService contactsService, int NbrContactEdit)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
_contactService = contactsService;
BindingContext = new EditNumberViewModel(SelectedEdit, contactsService, NbrContactEdit);
nbrEditContact.Text = "Le nombre de contact modifié est: " + NbrContactEdit;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// 806. Number of Lines To Write String
/// </summary>
namespace ConsoleApp4
{
class NumberOfLinesToWriteString
{
public static int[] NumberOfLines(int[] widths, string S)
{
int lines = 1, units = 0;
for (int i = 0; i < S.Length; i++)
{
units += widths[S[i] - 'a'];
if (units > 100)
{
units = 0; ;
lines++;
i--;
}
}
return new int[] { lines, units };
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Gms.Maps.Model;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Util;
namespace Geofence
{
public class Constants
{
private Constants()
{
}
public static string PACKAGE_NAME = "com.google.android.gms.location.Geofence";
public static string SHARED_PREFERENCES_NAME = PACKAGE_NAME + ".SHARED_PREFERENCES_NAME";
public static string GEOFENCES_ADDED_KEY = PACKAGE_NAME + ".GEOFENCES_ADDED_KEY";
public static long GEOFENCE_EXPIRATION_IN_HOURS = 12;
public static long GEOFENCE_EXPIRATION_IN_MILLISECONDS = GEOFENCE_EXPIRATION_IN_HOURS * 60 * 60 * 1000;
public static float GEOFENCE_RADIUS_IN_METERS = 1609;
public static Dictionary<string, LatLng> BAY_AREA_LANDMARKS = new Dictionary<string, LatLng>()
{
{"SFO", new LatLng(37.621313, -122.378955)},
{"GOOGLE", new LatLng(37.422611, -122.0840577)}
};
//ADD YOUR OWN LOCAL COORDINATES HERE TO TEST OUT THE SERVICE
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SQMS.Services;
using EasyDev.Util;
using System.Data;
using EasyDev.SQMS;
namespace SQMS.Application.Views.Basedata
{
public partial class OrganizationView : SQMSPage<OrganizationService>
{
private OrganizationService srv = null;
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnPreInitializeViewEventHandler(object sender, EventArgs e)
{
srv = Service as OrganizationService;
}
protected override void OnInitializeViewEventHandler(object sender, EventArgs e)
{
DataRow drEmployee = DataSetUtil.GetFirstRowFromDataSet(this.ViewData, "ORGANIZATION");
if (drEmployee != null)
{
this.lblOrgName.Text = ConvertUtil.ToStringOrDefault(drEmployee["ORGNAME"]);
this.lblOrgCode.Text = ConvertUtil.ToStringOrDefault(drEmployee["ORGCODE"]);
this.lblOrgClass.Text = ConvertUtil.ToStringOrDefault(drEmployee["ORGTYPE"]);
this.lblOrgParent.Text = ConvertUtil.ToStringOrDefault(drEmployee["PARENTORG"]);
this.lblOrgAlias.Text = ConvertUtil.ToStringOrDefault(drEmployee["ORGALIAS"]);
this.lblOrgContact.Text = ConvertUtil.ToStringOrDefault(drEmployee["CONTACT"]);
this.lblOrgConatctTel.Text = ConvertUtil.ToStringOrDefault(drEmployee["CONTACTTEL"]);
this.lblOrgZIP.Text = ConvertUtil.ToStringOrDefault(drEmployee["ZIPCODE"]);
this.lblOrgADD.Text = ConvertUtil.ToStringOrDefault(drEmployee["ORGADDRESS"]);
this.lblOrgStatus.Text = ConvertUtil.ToStringOrDefault(drEmployee["ORGSTATUS"]);
this.lblOrgMemo.Text = ConvertUtil.ToStringOrDefault(drEmployee["MEMO"]);
this.lblOrgIsVoid.Text = ConvertUtil.ToStringOrDefault(drEmployee["ISVOID"]).Equals("Y") ? "禁用" : "启用";
}
}
protected override void OnLoadDataEventHandler(object sender, EventArgs e)
{
this.ViewData = Service.LoadByKey(this.ID, true);
}
public void btnDelete_OnClick(object sender, EventArgs e)
{
try
{
//设置引用到它的节点
srv.SetParent2null(this.ID);
//ORG
srv.DeleteByKey(this.ID);
}
catch (System.Exception ex)
{
throw ex;
}
Response.Redirect("OrganizationList.aspx?p=organizationlist");
}
public void btnEdit_Click(object sender, EventArgs e)
{
Response.Redirect("OrganizationEdit.aspx?p=organizationedit&id=" + this.ID);
}
public void btnNew_Click(object sender, EventArgs e)
{
Response.Redirect("OrganizationEdit.aspx?p=organizationnew");
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
using Comics.Core.Persistence;
using Comics.Core.Presentation;
using HtmlAgilityPack;
using NFluent;
using Xunit;
namespace Comics.Tests.Core.Presentation
{
public class ComicFeedTests
{
[Fact]
public void ItContainsATitle()
{
var feed = new ComicFeed("Explosm Comic Feed", new Uri("http://example.com"));
var xml = feed.Render(Enumerable.Empty<Comic>());
var rss = ReadRssXml(xml);
Check.That(rss.Title.Text).IsEqualTo("Explosm Comic Feed");
}
[Fact]
public void CanSetDescription()
{
var feed = new ComicFeed("Explosm Comic Feed", new Uri("http://example.com"));
feed.Description = "Feed Description";
var xml = feed.Render(Enumerable.Empty<Comic>());
var rss = ReadRssXml(xml);
Check.That(rss.Description.Text).IsEqualTo("Feed Description");
}
[Fact]
public void PassedInItemsTurnIntoFeedItems()
{
var feed = new ComicFeed("Foobar", new Uri("http://abc.def"));
var xml = feed.Render(Enumerable.Repeat(new Comic()
{
Permalink = "http://example.com/"
}, 5));
var rss = ReadRssXml(xml);
Check.That(rss.Items).HasSize(5);
}
[Fact]
public void ItemHasComicsDateAsName()
{
var feed = new ComicFeed("Foobar", new Uri("http://abc.def"));
var xml = feed.Render(new[]
{
new Comic()
{
PublishedDate = new DateTime(2015, 5, 16),
Permalink = "http://example.com/"
}
});
var rss = ReadRssXml(xml);
Check.That(rss.Items.Single().Title.Text).IsEqualTo("2015-05-16");
}
[Fact]
public void ItemLinksToPermalink()
{
var feed = new ComicFeed("Foobar", new Uri("http://abc.def"));
var xml = feed.Render(new[]
{
new Comic() { Permalink = "http://www.google.com/" }
});
var rss = ReadRssXml(xml);
Check.That(rss.Items.Single().Links.First().Uri.ToString()).IsEqualTo("http://www.google.com/");
}
[Fact]
public void ContentHasImageTagWithSource()
{
var feed = new ComicFeed("Foobar", new Uri("http://abc.def"));
var xml = feed.Render(new[]
{
new Comic()
{
Permalink = "http://www.google.com/",
ImageSrc = "http://example.com/image.png"
}
});
var rss = ReadRssXml(xml);
var doc = new HtmlDocument();
doc.LoadHtml(rss.Items.First().Summary.Text);
var img = doc.QuerySelector("img");
Check.That(img.GetAttributeValue("src", null)).IsEqualTo("http://example.com/image.png");
}
private SyndicationFeed ReadRssXml(string xml)
{
using (var reader = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(xml))))
{
return SyndicationFeed.Load(reader);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Web.student
{
public partial class seleted : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string str = e.Row.Cells[5].Text;
if (str== " ")
{
e.Row.Cells[5].Text = "未录入成绩";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//for (int i= 0;i< GridView1.Rows.Count; i++)
//{
// string score = GridView1.Rows[i].Cells[5].Text;
// CheckBox chb = GridView1.Rows[i].Cells[6].FindControl("CheckBox1") as CheckBox;
// if(score== " "&&)
//}
}
}
} |
using BugunNeYesem.Data;
using BugunNeYesem.Logic;
using BugunNeYesem.Logic.Utils;
using FakeItEasy;
using NUnit.Framework;
namespace BugunNeYesem.Test
{
[TestFixture]
public class NotificationServiceTests
{
[Test]
public void NotificationService_NotifyFlowdock_ReturnsTrue()
{
//arrange
var emailSender = A.Fake<IEmailSender>();
var notificationService = new NotificationService(emailSender);
var recommendedRestaurant = new RecommendedRestaurant
{
RestaurantName = "Adres",
Address = "Bulgurlu Mahallesi, Bulgurlu Caddesi, No 105/A, Üsküdar, İstanbul",
Phone = "0 216 461 99 55",
EditorRating = "4"
};
//act
var result = notificationService.NotifyFlowdockWithRecomendation(recommendedRestaurant);
//assert
Assert.IsTrue(result);
}
}
} |
namespace MatchNumbers
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class StartUp
{
public static void Main()
{
var numbersList = Console.ReadLine();
var pattern = @"(^|(?<=\s))-?(\d+)(\.\d+)?($|(?=\s))";
var matchesNums = Regex.Matches(numbersList, pattern);
var validNumbers = matchesNums
.Cast<Match>()
.Select(x => x.Value)
.ToArray();
Console.WriteLine(string.Join(" ", validNumbers));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SortObject : MonoBehaviour {
[SerializeField]
private GameObject[] _sortGameObjects;
public static List<GameObject> sortGameObjects = new List<GameObject> ();
// Start is called before the first frame update
void Start () {
sortGameObjects.Add (gameObject);
}
// Update is called once per frame
void Update () {
sortGameObjects.RemoveAll (x => x == null);
sortGameObjects.Sort (delegate (GameObject j1, GameObject j2) {
return j1.transform.position.y < j2.transform.position.y ? 1 : -1;
});
for (int i = 0; i < sortGameObjects.Count; i++) {
sortGameObjects[i].GetComponent<SpriteRenderer> ().sortingOrder = i;
}
_sortGameObjects = sortGameObjects.ToArray ();
}
} |
using Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Models;
using System.Collections.Generic;
namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Comparer
{
public class TqRegistrationPathwayEqualityComparer : IEqualityComparer<TqRegistrationPathway>
{
//private TqRegistrationSpecialismEqualityComparer _tqRegistrationSpecialismComparer;
//public TqRegistrationPathwayEqualityComparer()
//{
// _tqRegistrationSpecialismComparer = new TqRegistrationSpecialismEqualityComparer();
//}
public bool Equals(TqRegistrationPathway x, TqRegistrationPathway y)
{
if (x == null && x == null)
return true;
else if (x == null || x == null)
return false;
else if (x.GetType() != y.GetType())
return false;
else
{
var retVal =
//x.TqRegistrationProfileId == y.TqRegistrationProfileId &&
x.TqProviderId == y.TqProviderId
&& Equals(x.StartDate, y.StartDate)
&& Equals(x.EndDate, y.EndDate)
&& x.Status == y.Status;
return retVal;
}
}
public int GetHashCode(TqRegistrationPathway regPathway)
{
unchecked
{
var hashCode = regPathway.TqProviderId.GetHashCode();
//var hashCode = regPathway.TqRegistrationProfileId.GetHashCode();
//hashCode = (hashCode * 397) ^ regPathway.TqProviderId.GetHashCode();
hashCode = (hashCode * 397) ^ regPathway.StartDate.GetHashCode();
hashCode = (hashCode * 397) ^ (regPathway.EndDate != null ? regPathway.EndDate.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ regPathway.Status.GetHashCode();
//foreach (var registrationSpecialism in regPathway.TqRegistrationSpecialisms)
//{
// hashCode = (hashCode * 397) ^ _tqRegistrationSpecialismComparer.GetHashCode(registrationSpecialism);
//}
return hashCode;
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Pitcher : MonoBehaviour {
public GameObject ball;
public GameObject curve;
public float power = 100f;
public Vector3 direction;
public int busu;
void Start () {
StartCoroutine (Spawn ());
}
IEnumerator Spawn(){
while (true) {
busu = Random.Range (1, 5);
if(busu == 1){
var obj = Instantiate (ball, ball.transform.position,Quaternion.identity) as GameObject;
var rigidbody = obj.GetComponent<Rigidbody>();
rigidbody.AddForce (direction * power, ForceMode.Impulse);
}else if(busu >= 2){
Instantiate (curve);
}
yield return new WaitForSeconds(10f);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using System.IO;
using System.Text.RegularExpressions;
namespace CA1StreamReaderWriter
{
class Program
{
static void Main(string[] args)
{
//declare variables
string pat = @"-{72}"; //hyphen pattern
string filepath = @"D:\Adv Prog\Advanced-Programming\commit-changes.txt"; //user to update?
string[] separator = { "|" }; //for string split functions
string[] lines = System.IO.File.ReadAllLines(filepath);//create an array of all lines in the file
int counter = 0; //use to move through the lines in the file
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ System.IO.Path.DirectorySeparatorChar + @"commit-changes.csv";
//instantiate classes
MyMethods methods = new MyMethods();
CommitList cl = new CommitList();
Regex filebreakpattern = new Regex(pat);
try
{
//iterate through all lines and parse into ref, author, date, comments and changedpaths
while (counter < lines.Length - 1)
{
if (filebreakpattern.IsMatch(lines[counter].ToString()))//check if hyphen pattern
{
counter++; //no of the line after hyphens
//split the first line of each commit into array
string split = lines[counter].ToString();
string[] myarr = split.Split(separator, StringSplitOptions.RemoveEmptyEntries);
//trim each string stored in the array to remove extra spaces
myarr = methods.TrimArrayStrings(myarr);
//remove extra information from date - allows for conversion to DateTime if required
myarr[2] = myarr[2].Substring(0, 19);
//move the reader to start of file paths changed
counter++;
methods.SkipLines(lines, ref counter, "Changed paths:");
//create array of paths changed
string[] changedPaths = methods.MyStringBuilder(lines, ref counter, pat).ToString().Split(separator, StringSplitOptions.RemoveEmptyEntries);
changedPaths = methods.TrimArrayStrings(changedPaths);
//move counter to start of comment section
methods.SkipLines(lines, ref counter);
//combine all comment lines into one string
string comment = methods.MyStringBuilder(lines, ref counter, pat).ToString().Trim();
//add individual commit details to commit list
cl.AddToList(myarr[0], myarr[1], myarr[2], /*noOfLines,*/ comment, changedPaths);
}
else
{
counter++;
}
}
}//end of try for read file
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
//write out parsed data to csv file
methods.WriteListToFile(CommitList.commitList, filePath, true);
//confirm whether file has been successfully updated or not
Console.WriteLine("File created or updated successfully - total number of commit records is {0}", CommitList.commitList.Count());
//used to check parsing of file before writing to file
//foreach (var commit in CommitList.commitList)
//{
// Console.WriteLine(commit.ToString());
//}
Console.ReadLine();
}//end of write to file try
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace League.Models
{
public class Ninja
{
[Key]
public long id { get; set; }
[Required]
[MinLength(3, ErrorMessage = "Name must be at least 3 characters")]
[Display(Name = "Name")]
public string name { get; set; }
[Required]
[Range(1, 5, ErrorMessage = "Level must be between 1 and 5")]
[Display(Name = "Level")]
public int level { get; set; }
[Required]
[Display(Name = "Description")]
public string description { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
[Required]
[Display(Name = "Dojo")]
public int dojo_id { get; set; }
public Dojo dojo { get; set; }
public string dojo_name { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EZCameraShake;
public class boundaryShake : MonoBehaviour
{
public float magnitude = 3f;
public counter count;
private void OnCollisionEnter2D()
{
CameraShaker.Instance.ShakeOnce(magnitude, 4f, .1f, 1f);
count.increaseScore();
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
namespace WebRole1
{
public class Storage
{
private CloudStorageAccount storageAccount;
private CloudQueue queue;
private CloudTable table;
public Storage(string conString)
{
storageAccount = CloudStorageAccount.Parse(conString);
}
public CloudQueue getQueue(string name)
{
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
queue = queueClient.GetQueueReference(name);
return queue;
}
public CloudTable getTable(string name)
{
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
table = tableClient.GetTableReference(name);
return table;
}
}
} |
namespace CODE.Framework.Wpf.TestBench
{
/// <summary>
/// Interaction logic for TabItemsPanelTest.xaml
/// </summary>
public partial class TabItemsPanelTest
{
public TabItemsPanelTest()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Construction_Project
{
public partial class RegistrationPage : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
//sign up button click event
protected void Button1_Click(object sender, EventArgs e)
{
if (checkEmployeeExists())
{
Response.Write("<script>alert('Member Already Exist with this Member ID, try other ID');</script>");
clearData();
}
else
{
signUpNewEmployee();
}
}
bool checkEmployeeExists()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM Permanent_Employee WHERE userName = '" + TextBox7.Text + "';", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count >= 1)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
return false;
}
}
void signUpNewEmployee()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("INSERT INTO Permanent_Employee(FirstName,LastName,DateOfBirth,ContactNumber,Email,Designation,Qualifications,userName,Password) " +
"VALUES('" + TextBox1.Text + "' ,'" + TextBox2.Text + "' , '" + TextBox3.Text + "' , '" + TextBox4.Text + "' , '" + TextBox5.Text + "' , '" + DropDownList1.SelectedItem.Value + "' , '" + TextBox6.Text + "' , '" + TextBox7.Text + "' , '" + TextBox8.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Sign Up Successful. Go to User Login to Login');</script>");
clearData();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
void clearData()
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
DropDownList1.SelectedItem.Value = "";
TextBox6.Text = "";
TextBox7.Text = "";
TextBox8.Text = "";
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CYJ.Utils.Extension.LinqExtension
{
public static class EnumerableExtension
{
/// <summary>合并两个IEnumerable不同元素.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>
/// An enumerator that allows foreach to be used to process merge distinct inner
/// enumerable in this collection.
/// </returns>
public static IEnumerable<T> MergeDistinctInnerEnumerable<T>(this IEnumerable<IEnumerable<T>> @this)
{
var listItem = @this.ToList();
var list = new List<T>();
foreach (var item in listItem) list = list.Union(item).ToList();
return list;
}
/// <summary>合并两个IEnumerable不同元素</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>
/// An enumerator that allows foreach to be used to process merge inner enumerable in
/// this collection.
/// </returns>
public static IEnumerable<T> MergeInnerEnumerable<T>(this IEnumerable<IEnumerable<T>> @this)
{
var listItem = @this.ToList();
var list = new List<T>();
foreach (var item in listItem) list.AddRange(item);
return list;
}
/// <summary>
/// 判断当前IEnumerable是否包含指定的所有元素
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public static bool IsContainsAll<T>(this IEnumerable<T> @this, params T[] values)
{
var list = @this.ToArray();
foreach (var value in values)
if (!list.Contains(value))
return false;
return true;
}
/// <summary>
/// 判断当前IEnumerable是否包含指定的数组任一元素
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
public static bool IsContainsAny<T>(this IEnumerable<T> @this, params T[] values)
{
var list = @this.ToArray();
foreach (var value in values)
if (list.Contains(value))
return true;
return false;
}
/// <summary>
/// 遍历操作当前IEnumerable每一项
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="action">The action.</param>
/// <returns>An enumerator that allows foreach to be used to process for each in this collection.</returns>
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
var array = @this.ToArray();
foreach (var t in array) action(t);
return array;
}
/// <summary>遍历操作当前IEnumerable每一项</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="action">The action.</param>
/// <returns>An enumerator that allows foreach to be used to process for each in this collection.</returns>
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> @this, Action<T, int> action)
{
var array = @this.ToArray();
for (var i = 0; i < array.Length; i++) action(array[i], i);
return array;
}
/// <summary>
/// 判断IEnumerable 是否没有元素
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The collection to act on.</param>
/// <returns>true if empty, false if not.</returns>
public static bool IsEmpty<T>(this IEnumerable<T> @this)
{
return !@this.Any();
}
/// <summary>
/// 判断IEnumerable 是否有元素
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The collection to act on.</param>
/// <returns>true if a not is t>, false if not.</returns>
public static bool IsNotEmpty<T>(this IEnumerable<T> @this)
{
return @this.Any();
}
/// <summary>
/// 判断IEnumerable 是否有元素且不为Null
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The collection to act on.</param>
/// <returns>true if a not null or is t>, false if not.</returns>
public static bool IsNotNullOrEmpty<T>(this IEnumerable<T> @this)
{
return @this != null && @this.Any();
}
/// <summary>
/// 判断IEnumerable 是否没有元素或者为Null
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The collection to act on.</param>
/// <returns>true if a null or is t>, false if not.</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> @this)
{
return @this == null || !@this.Any();
}
/// <summary>
/// 使用指定的分隔符连接 IEnumerable 的所有元素
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">An IEnumerable that contains the elements to concatenate.</param>
/// <param name="separator">
/// The string to use as a separator. separator is included in the returned string only if
/// value has more than one element.
/// </param>
/// <returns>
/// A string that consists of the elements in value delimited by the separator string. If value is an empty array,
/// the method returns String.Empty.
/// </returns>
public static string StringJoin<T>(this IEnumerable<T> @this, string separator)
{
return string.Join(separator, @this);
}
/// <summary>
/// 使用指定的分隔符连接 IEnumerable 的所有元素
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <param name="separator">
/// The string to use as a separator. separator is included in the
/// returned string only if value has more than one element.
/// </param>
/// <returns>
/// A string that consists of the elements in value delimited by the separator string. If
/// value is an empty array, the method returns String.Empty.
/// </returns>
public static string StringJoin<T>(this IEnumerable<T> @this, char separator)
{
return string.Join(separator.ToString(), @this);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace DotNetCoreIdentity.Application
{
public class EntityDto<T> : CommonEntityDto
{
public T Id { get; set; }
}
// default base dto
public class EntityDto : CommonEntityDto
{
public int Id { get; set; }
}
public class CommonEntityDto
{
[Display(Name = "Oluşturma Tarihi")]
public DateTime CreatedDate { get; set; } = DateTime.UtcNow;
[Display(Name = "Son Güncelleme")]
public DateTime? ModifiedDate { get; set; }
[Display(Name = "Oluşturan Kullanıcı")]
public string CreatedBy { get; set; }
public string CreatedById { get; set; }
[Display(Name = "Düzenleyen Kullanıcı")]
public string ModifiedBy { get; set; }
public string ModifiedById { get; set; }
}
}
|
using GardenControlCore.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GardenControlApi.Models
{
public class RelaySetStateDto
{
public int DeviceId { get; set; }
public RelayState State { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace PizzeriaApi.Models
{
public partial class Stan
{
public int IdStan { get; set; }
public string Nazwa { get; set; }
public TimeSpan PozostalyCzas { get; set; }
}
}
|
using System.Threading.Tasks;
using FrontDesk.Infrastructure.Data;
using UnitTests.Builders;
using Xunit;
namespace IntegrationTests.ClientTests
{
public class EfRepositoryGetById : BaseEfRepoTestFixture
{
private readonly EfRepository _repository;
public EfRepositoryGetById()
{
_repository = GetRepositoryAsync().Result;
}
[Fact]
public async Task GetsByIdClientAfterAddingIt()
{
var id = 9;
var client = await AddClient(id);
var newClient = await _repository.GetByIdAsync<FrontDesk.Core.Aggregates.Client, int>(id);
Assert.Equal(client, newClient);
Assert.True(newClient?.Id == id);
}
private async Task<FrontDesk.Core.Aggregates.Client> AddClient(int id)
{
var client = new ClientBuilder().Id(id).Build();
await _repository.AddAsync<FrontDesk.Core.Aggregates.Client, int>(client);
return client;
}
}
}
|
using Google.OrTools.LinearSolver;
using System;
namespace capacited_facility_location_problem
{
internal class FacilityOptimizer
{
public FacilityOptimizer()
{
}
internal object SolveProblemForInstance(FacilityProblemData facilityProblemInstance)
{
// TODO: add heuristics
var ortoolsSolver = new FacilityMIPModelBuilder().BuildSolverForInstance(facilityProblemInstance);
ortoolsSolver.EnableOutput();
var a = new MPSolverParameters();
a.SetDoubleParam(0, 80);
ortoolsSolver.SetTimeLimit(1000 * 60 * 5);
//Console.WriteLine(ortoolsSolver.ExportModelAsMpsFormat(true, false));
//Console.WriteLine(ortoolsSolver.ExportModelAsLpFormat(false));
ortoolsSolver.Solve(a);
return new ResultBuider().BuildResultFromOrToolsSolverAndProblemInstance(ortoolsSolver, facilityProblemInstance);
}
}
} |
using NGeoNames.Entities;
using System.Globalization;
namespace NGeoNames.Composers
{
/// <summary>
/// Provides methods for composing a string representing an <see cref="ExtendedGeoName"/>.
/// </summary>
public class ExtendedGeoNameComposer : BaseComposer<ExtendedGeoName>
{
/// <summary>
/// Composes the specified <see cref="ExtendedGeoName"/> into a string.
/// </summary>
/// <param name="value">The <see cref="ExtendedGeoName"/> to be composed into a string.</param>
/// <returns>A string representing the specified <see cref="ExtendedGeoName"/>.</returns>
public override string Compose(ExtendedGeoName value)
{
return string.Join(this.FieldSeparator.ToString(), value.Id, value.Name, value.NameASCII, ArrayToValue(value.AlternateNames),
value.Latitude.ToString(CultureInfo.InvariantCulture), value.Longitude.ToString(CultureInfo.InvariantCulture), value.FeatureClass, value.FeatureCode, value.CountryCode,
ArrayToValue(value.AlternateCountryCodes), value.Admincodes[0], value.Admincodes[1], value.Admincodes[2], value.Admincodes[3],
value.Population, value.Elevation, value.Dem, value.Timezone.Replace(" ", "_"), value.ModificationDate.ToString("yyyy-MM-dd"));
}
}
}
|
using FriendStorage.DataAccess;
using FriendStorage.UI.Command;
using FriendStorage.UI.DataProvider;
using FriendStorage.UI.Events;
using Prism.Events;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
namespace FriendStorage.UI.ViewModel
{
public class MainViewModel : ViewModelBase
{
private readonly Func<IFriendEditViewModel> _friendEditViewModelFactory;
private readonly IEventAggregator _eventAggregator;
public IFriendEditViewModel SelectedFriendEditViewModel { get; set; }
public INavigationViewModel NavigationViewModel { get; private set; }
public ObservableCollection<IFriendEditViewModel> FriendEditViewModels { get; }
= new ObservableCollection<IFriendEditViewModel>();
public ICommand CloseFriendTabCommand { get; private set; }
public ICommand AddFriendCommand { get; private set; }
public MainViewModel(INavigationViewModel navigationViewModel,
Func<IFriendEditViewModel> friendEditViewModelFactory,
IEventAggregator eventAggregator)
{
NavigationViewModel = navigationViewModel;
_friendEditViewModelFactory = friendEditViewModelFactory;
_eventAggregator = eventAggregator;
eventAggregator.GetEvent<OpenFriendEditViewEvent>().Subscribe(OnOpenFriendEditView);
eventAggregator.GetEvent<FriendDeletedEvent>().Subscribe(OnFriendDeleted);
CloseFriendTabCommand = new DelegateCommand(OnCloseFriendTabExecute);
AddFriendCommand = new DelegateCommand(OnAddFriendExecute);
}
private void OnFriendDeleted(int friendId)
{
var friendEditVm = FriendEditViewModels.Single(vm => vm.Friend.Id == friendId);
FriendEditViewModels.Remove(friendEditVm);
}
private void OnCloseFriendTabExecute(object obj)
{
var friendEditVm = (IFriendEditViewModel)obj;
FriendEditViewModels.Remove(friendEditVm);
}
private void OnOpenFriendEditView(int friendId)
{
var friendEditVm = FriendEditViewModels.FirstOrDefault(f => f.Friend.Id == friendId) ??
CreateAndLoadFriendEditViewModel(friendId);
SelectedFriendEditViewModel = friendEditVm;
}
private void OnAddFriendExecute(object obj)
{
SelectedFriendEditViewModel = CreateAndLoadFriendEditViewModel(null);
}
private IFriendEditViewModel CreateAndLoadFriendEditViewModel(int? friendId)
{
var friendEditVm = _friendEditViewModelFactory();
FriendEditViewModels.Add(friendEditVm);
friendEditVm.Load(friendId);
return friendEditVm;
}
public void Load()
{
NavigationViewModel.Load();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Patterns.Pattern.Ef6;
namespace Welic.Dominio.Models.Segurança.Map
{
public enum TypeProgram
{
Cadastro = 1,
processo = 2,
relatorio = 3,
}
public class ProgransMap : Entity
{
public int IdProgram { get; set; }
public string Description { get; set; }
public TypeProgram Type { get; set; }
public bool Active { get; set; }
public virtual ICollection<PermissionMap> Permission { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OK_GameManager : MonoBehaviour {
// Var for timer
private float startTime;
private float fl_Time;
// Var Gameobjects that turn on/off
public GameObject Console_Idle;
public GameObject Console1;
public GameObject Console2;
public GameObject Console3;
public GameObject Console4;
public GameObject ScreenIdle;
public GameObject Screen;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
TimerScene();
}
#region Timer
// Allows for us to time the scene.
void TimerScene()
{
fl_Time = Time.time - startTime;
string minutes = ((int)fl_Time / 60).ToString();
string seconds = (fl_Time % 60).ToString("f2");
Debug.Log(minutes + ":" + seconds);
if (fl_Time >= 180)
{
Screen.SetActive(true);
ScreenIdle.SetActive(false);
}
else if (fl_Time >= 120)
{
Console4.SetActive(true);
Console_Idle.SetActive(false);
}
else if (fl_Time >= 90)
{
Console3.SetActive(true);
Console_Idle.SetActive(false);
}
else if (fl_Time >= 60)
{
Console2.SetActive(true);
Console_Idle.SetActive(false);
}
else if (fl_Time >= 30)
{
Console1.SetActive(true);
Console_Idle.SetActive(false);
}
}
#endregion
}
|
using _01_Alabo.Cloud.Core.SendSms.Domain.Enums;
namespace _01_Alabo.Cloud.Core.SendSms.Dtos
{
public class SmsInput
{
/// <summary>
/// 类型
/// </summary>
public SmsType Type { get; set; } = SmsType.Phone;
/// <summary>
/// 手机号码 逗号隔开
/// </summary>
public string Phone { get; set; }
/// <summary>
/// 消息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 发送状态
/// </summary>
public SendState State { get; set; } = SendState.Root;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CountBonsObject : SingletonComponent<CountBonsObject>
{
int BonusObejctCount;
public void CountUp()
{
BonusObejctCount++;
}
public void ReSet()
{
BonusObejctCount = 0;
}
public int GetBonusObejctCount()
{
return BonusObejctCount;
}
}
|
using Alabo.Web.Mvc.Attributes;
namespace Alabo.Framework.Core.Enums.Enum {
[ClassProperty(Name = "传参类型")]
public enum AuthorityType {
Get,
Post
}
} |
using UnityEngine;
using System.Collections;
namespace zm.Questioning
{
public abstract class AnswerRendererBase : MonoBehaviour
{
#region Fields and Properties
protected Answer answer;
public virtual Answer Answer
{
set
{
answer = value;
}
get
{
return answer;
}
}
#endregion Fields and Properties
}
} |
using Microsoft.EntityFrameworkCore;
using ServiceQuotes.Domain.Entities;
using ServiceQuotes.Domain.Repositories;
using ServiceQuotes.Infrastructure.Context;
using System.Linq;
using System.Threading.Tasks;
namespace ServiceQuotes.Infrastructure.Repositories
{
public class SpecializationRepository : Repository<Specialization>, ISpecializationRepository
{
public SpecializationRepository(AppDbContext dbContext) : base(dbContext) { }
public async Task<Specialization> GetByName(string name)
{
return await _entities.Where(s => s.Name == name).SingleOrDefaultAsync();
}
}
}
|
using UnityEngine;
using UnityEngine.EventSystems;
public class TestDragImage : MonoBehaviour
, IPointerClickHandler
, IDragHandler
, IBeginDragHandler
, IEndDragHandler
{
private Vector3 mStartPosition;
private void Start()
{
mStartPosition = transform.position;
}
public void OnPointerClick( PointerEventData eventData )
{
Debug.Log( "Image Clicked" );
}
public void OnDrag( PointerEventData eventData )
{
Debug.Log( "Image Drag" );
transform.position = eventData.position;
}
public void OnBeginDrag( PointerEventData eventData )
{
Debug.Log( "Image Begin Drag" );
}
public void OnEndDrag( PointerEventData eventData )
{
Debug.Log( "Image End Drag" );
transform.position = mStartPosition;
}
}
|
using System.CodeDom.Compiler;
namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution
{
[GeneratedCode("wsdl", "2.0.50727.42")]
public delegate void LoadDrillthroughTarget3CompletedEventHandler(object sender, LoadDrillthroughTarget3CompletedEventArgs e);
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SOP_IAA_DAL
{
[MetadataType(typeof(personaMetaData))]
public partial class persona
{
}
public class personaMetaData
{
[Required]
[DisplayName("Nombre")]
[StringLength(50)]
public string nombre { get; set; }
[Required]
[DisplayName("Primer Apellido")]
[StringLength(50)]
public string apellido1 { get; set; }
[Required]
[DisplayName("Segundo Apellido")]
[StringLength(50)]
public string apellido2 { get; set; }
[DisplayName("Cédula")]
[StringLength(50)]
public string cedula { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Vector vector1 = new Vector(25, 30);
Vector vector2 = new Vector(22, 29);
Vector sum = new Vector();
sum = Vector.Add(vector1, vector2);
return vector1;
}
}
}
|
using EmberKernel.Services.Command.Parsers;
using System;
using System.Collections.Generic;
using System.Text;
namespace EmberKernel.Services.Command.Attributes
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class CommandParserAttribute : Attribute
{
public Type Parser { get; }
public CommandParserAttribute(Type parser)
{
this.Parser = parser;
}
}
}
|
using System.Collections.Generic;
using NHibernate;
using Profiling2.Domain.Prf.Sources;
namespace Profiling2.Domain.Contracts.Queries
{
public interface IJhroCaseQueries
{
JhroCase GetJhroCase(ISession session, string caseNumber);
void SaveJhroCase(ISession session, JhroCase jhroCase);
IList<JhroCase> SearchJhroCases(string term);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace WhatToDevelop
{
public class MainViewModel : Livet.ViewModel
{
public static MainViewModel Current;
private List<Model.Raw.ItemInfo> Content;
#region 交互属性
public ObservableCollection<Model.ViewItem> List { get; private set; } = new ObservableCollection<Model.ViewItem>();
private Model.ViewItem _selected;
public Model.ViewItem SelectedItem
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged();
RaisePropertyChanged("AvailableVisibility");
}
}
public bool HasError => _error != null;
private string _error = null;
public string ErrorDescr
{
get { return _error; }
private set
{
_error = value;
RaisePropertyChanged();
}
}
private DateTime _date = DateTime.Today;
public DateTime Date
{
get { return _date; }
set
{
_date = value;
RaisePropertyChanged("WeekCn");
RaisePropertyChanged("WeekJp");
RefreshList();
}
}
public bool AvailableVisibility => SelectedItem?.OtherTarget ?? false;
public string WeekCn
{ get { return weekCn[Convert.ToInt32(Date.DayOfWeek)]; } }
public string WeekJp
{ get { return weekJp[Convert.ToInt32(Date.DayOfWeek)]; } }
public List<string> Favorite { get; private set; } = new List<string>();
#endregion
private static readonly FileInfo file = new FileInfo(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"grabacr.net",
"KanColleViewer",
"WTD_Favorite.xml"));
public MainViewModel()
{
Current = this;
Task.Run(() =>
{
if (!file.Exists)
return;
XmlSerializer se = new XmlSerializer(typeof(List<string>));
using (FileStream fs = new FileStream(file.FullName, FileMode.Open))
Favorite = se.Deserialize(fs) as List<string>;
});
Task.Run(() =>
{
using (HttpClient client = new HttpClient())
{
DataContractJsonSerializer se = new DataContractJsonSerializer(typeof(Model.Raw.OdataContainer));
using (Stream rep = client.GetStreamAsync("https://www.smdhz.cf/odata/ItemInfoes?$expand=ItemNo2Info").Result)
Content = (se.ReadObject(rep) as Model.Raw.OdataContainer).value.ToList();
}
RefreshList();
});
}
private readonly static string[] weekCn = new string[7] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
private readonly static string[] weekJp = new string[7] { "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" };
/// <summary>
/// 刷新道具列表
/// </summary>
public void RefreshList()
{
System.Windows.Application.Current.Dispatcher.Invoke(() => List.Clear());
foreach (Model.ViewItem i in Content
.Where(j => j.ItemNo2Info.SelectMany(k => k.Weekdays.Split(',').Select(int.Parse)).Contains(Convert.ToInt32(Date.DayOfWeek)))
.Select(j => new Model.ViewItem(j))
.OrderByDescending(j => j.Favorite)
.ThenBy(j => Enum.Parse(typeof(Grabacr07.KanColleWrapper.Models.SlotItemIconType), j.Icon))
.ToList())
{
System.Windows.Application.Current.Dispatcher.Invoke(() => List.Add(i));
}
}
/// <summary>
/// 保持偏好信息
/// </summary>
/// <param name="value"></param>
public void SaveFavorite(bool value)
{
if (value)
Favorite.Add(SelectedItem.Name);
else
Favorite.Remove(SelectedItem.Name);
if (!file.Directory.Exists)
file.Directory.Create();
XmlSerializer se = new XmlSerializer(typeof(List<string>));
using (FileStream fs = new FileStream(file.FullName, FileMode.Create))
se.Serialize(fs, Favorite);
RefreshList();
}
}
}
|
using Contracts;
using Entities;
using Entities.Models;
namespace Repository
{
public class ReportDataEntryRepository : RepositoryBase<ReportDataEntry>, IReportDataEntryRepository
{
public ReportDataEntryRepository(RepositoryContext repositoryContext)
: base(repositoryContext)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace com.Sconit.Entity
{
public class Message
{
public CodeMaster.MessageType MessageType { get; set; }
private string messageKey { get; set; }
private string[] messageParams { get; set; }
public Message(CodeMaster.MessageType messageType, string messageKey, params string[] messageParams)
{
this.MessageType = messageType;
this.messageKey = messageKey;
this.messageParams = messageParams;
}
public string GetMessageString()
{
try
{
return messageParams == null || messageParams.Count() == 0 ? messageKey : string.Format(messageKey, messageParams);
}
catch (System.Exception ex)
{
return string.Empty;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Threading;
using UnityEngine.SceneManagement;
public class Timer : MonoBehaviour
{
public int timeLeft = 60;
public Text countdown;
void Start()
{
StartTimer();
}
public void StartTimer()
{
StartCoroutine(GainTime());
Time.timeScale = 1;
}
void Update()
{
// Create a temporary reference to the current scene.
Scene currentScene = SceneManager.GetActiveScene();
// Retrieve the name of this scene.
string sceneName = currentScene.name;
countdown.text = ("time: " + timeLeft);
if (timeLeft <= 0)
{
if (sceneName == "level-1")
{
SceneManager.LoadScene("level-2");
}
else if (sceneName == "level-2")
{
SceneManager.LoadScene("level-3");
}
else if (sceneName == "level-3")
{
SceneManager.LoadScene("winst");
}
else if (sceneName == "level-4")
{
timeLeft = 100000;
}
}
}
//Simple Coroutine
public IEnumerator GainTime()
{
while (true)
{
yield return new WaitForSeconds (1);
timeLeft--;
}
}
} |
public class Solution {
public int Trap(int[] height) {
int size = height.Length;
if (size == 0) return 0;
int[] left_max = new int[size];
int[] right_max = new int[size];
left_max[0] = height[0];
for (int i=1; i<size; i++) {
left_max[i] = Math.Max(height[i], left_max[i-1]);
}
right_max[size-1] = height[size-1];
for (int i=size-2; i>=0; i--) {
right_max[i] = Math.Max(height[i], right_max[i+1]);
}
int res=0;
for (int i=0; i<size; i++) {
res += Math.Min(left_max[i], right_max[i]) - height[i];
}
return res;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Unidade11.ExercicioFixacao
{
class OrdenarElemento
{
public static Random randNum = new Random();
static void Main111(string[] args)
{
int troca = 0;
int[] aux = new int[20];
int[] Nums = new int[20];
for (int i = 0; i < 20; i++)
{
aux[i] = randNum.Next(100,200);
Nums[i] = randNum.Next(1, 100);
troca = Nums[i];
aux[i] = troca;
}
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
namespace Ardunity
{
[AddComponentMenu("ARDUnity/Reactor/Transform/Rotation2DReactor")]
[HelpURL("https://sites.google.com/site/ardunitydoc/references/reactor/rotation2dreactor")]
public class Rotation2DReactor : ArdunityReactor
{
public bool invert = false;
private IWireInput<float> _analogInput;
private IWireOutput<float> _analogOutput;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if(_analogInput != null || _analogOutput != null)
{
if(_analogOutput != null)
{
if(invert)
_analogOutput.output = -transform.eulerAngles.z;
else
_analogOutput.output = transform.eulerAngles.z;
}
if(_analogInput != null)
{
Vector3 rot = transform.eulerAngles;
if(invert)
rot.z = -_analogInput.input;
else
rot.z = _analogInput.input;
transform.eulerAngles = rot;
}
}
}
protected override void AddNode(List<Node> nodes)
{
base.AddNode(nodes);
nodes.Add(new Node("setAngle", "Set Angle", typeof(IWireInput<float>), NodeType.WireFrom, "Input<float>"));
nodes.Add(new Node("getAngle", "Get Angle", typeof(IWireOutput<float>), NodeType.WireFrom, "Output<float>"));
}
protected override void UpdateNode(Node node)
{
if(node.name.Equals("setAngle"))
{
node.updated = true;
if(node.objectTarget == null && _analogInput == null)
return;
if(node.objectTarget != null)
{
if(node.objectTarget.Equals(_analogInput))
return;
}
_analogInput = node.objectTarget as IWireInput<float>;
if(_analogInput == null)
node.objectTarget = null;
return;
}
else if(node.name.Equals("getAngle"))
{
node.updated = true;
if(node.objectTarget == null && _analogOutput == null)
return;
if(node.objectTarget != null)
{
if(node.objectTarget.Equals(_analogOutput))
return;
}
_analogOutput = node.objectTarget as IWireOutput<float>;
if(_analogOutput == null)
node.objectTarget = null;
return;
}
base.UpdateNode(node);
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using System;
using System.Collections.Generic;
using System.Text;
namespace FiiiChain.DTO
{
public class ValidateAddressOM
{
public bool isValid { get; set; }
public string address { get; set; }
public string scriptPubKey { get; set; }
public bool isMine { get; set; }
public bool isWatchOnly { get; set; }
public bool isScript { get; set; }
public string script { get; set; }
public string hex { get; set; }
public string[] addresses { get; set; }
public int sigrequired { get; set; }
public string pubKey { get; set; }
public bool isCompressed { get; set; }
public string account { get; set; }
public string hdKeyPath { get; set; }
public string hdMasterKeyId { get; set; }
}
}
|
using System.Collections.Generic;
using alunosAPI.Models;
using alunosAPI.Repository;
using Microsoft.AspNetCore.Mvc;
namespace alunosAPI.Controllers
{
[Route("api/[Controller]")] //no navegador fica assim: https://localhost:5001/api/Materia
public class MateriaController : Controller
{
//Atributos:
private readonly IMateriaRepository materiaRepository;
//Construtor:
public MateriaController(IMateriaRepository materiaRepository)
{
this.materiaRepository = materiaRepository;
}
[HttpGet]
public IEnumerable<Materia> GetAll()
{
return materiaRepository.GetAll();
}
[HttpGet("{idmaterias}", Name = "GetMateria")]
public IActionResult GetById(long idmaterias)
{
// Buscando no materiaRepository pelo Id enviado no parametro
var materia = materiaRepository.Find(idmaterias);
if (materia == null)
//Checagem se for nulo
return NotFound(); //ERRO: 404
return new ObjectResult(materia);
}
[HttpPost]
public IActionResult Create([FromBody] Materia materia)
{
// Recebendo objeto materia no parametro
if (materia == null)
return BadRequest(); //ERRO: 400
// Adicionando ao repositorio caso não seja nulo
materiaRepository.Add(materia);
// Criação da rota
return CreatedAtRoute("GetPessoa", new { idmaterias = materia.idmaterias }, materia);
}
[HttpPut]
public IActionResult Update([FromBody] Materia materia)
{
// Recebe o objeto materia no parametro e busca no repositório para fazer o update
var materiaUpdate = materiaRepository.Find(materia.idmaterias);
if (materiaUpdate == null)
return NotFound(); //ERRO: 404
if (materia == null || materiaUpdate.idmaterias != materia.idmaterias)
return BadRequest(); //ERRO: 400
// Atualizar nome, periodo, carga horária de acordo com o idmaterias
materiaUpdate.nome = materia.nome;
materiaUpdate.periodo = materia.periodo;
materiaUpdate.carga_horaria = materia.carga_horaria;
materiaRepository.Update(materiaUpdate);
return new NoContentResult(); //SUCESSO: 204
}
[HttpDelete("{idmaterias}")]
public IActionResult Delete(long idmaterias)
{
// Fazer a deleção da materia de acordo com o seu id
var materiaDelete = materiaRepository.Find(idmaterias);
if (materiaDelete == null)
return NotFound(); //ERRO: 404
materiaRepository.Remove(idmaterias);
return new NoContentResult(); //SUCESSO: 204
}
}
} |
using Fbtc.Domain.Entities;
using System.Collections.Generic;
namespace Fbtc.Application.Interfaces
{
public interface ITipoPublicoApplication
{
IEnumerable<TipoPublico> GetAll(bool? isAtivo);
IEnumerable<TipoPublico> GetByTipoAssociacao(bool? associado);
TipoPublico GetTipoPublicoById(int id);
IEnumerable<TipoPublicoValorDao> GetTipoPublicoValorByEventoId(int id);
int GetIdTipoPublicoByCodigo(string codigo);
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace ShopApp.DataAccess.Migrations
{
public partial class order : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Address",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FullName = table.Column<string>(nullable: true),
Address1 = table.Column<string>(nullable: true),
City = table.Column<string>(nullable: true),
State = table.Column<string>(nullable: true),
Country = table.Column<string>(nullable: true),
PostalCode = table.Column<string>(nullable: true),
Phone = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
AddressType = table.Column<int>(nullable: false),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Address", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CreatedOn = table.Column<DateTime>(nullable: false),
OrderStatus = table.Column<int>(nullable: false),
BillingAddressId = table.Column<int>(nullable: true),
ShippingAddressId = table.Column<int>(nullable: true),
PaymentMethod = table.Column<string>(nullable: true),
PaymentMethodStatus = table.Column<string>(nullable: true),
ProductId = table.Column<int>(nullable: false),
CartId = table.Column<int>(nullable: false),
UserId = table.Column<string>(nullable: true),
Quantity = table.Column<int>(nullable: false),
Amount = table.Column<double>(nullable: false),
PaymentType = table.Column<string>(nullable: true),
DeliveryStatus = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Address_BillingAddressId",
column: x => x.BillingAddressId,
principalTable: "Address",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Orders_Carts_CartId",
column: x => x.CartId,
principalTable: "Carts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Address_ShippingAddressId",
column: x => x.ShippingAddressId,
principalTable: "Address",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_BillingAddressId",
table: "Orders",
column: "BillingAddressId");
migrationBuilder.CreateIndex(
name: "IX_Orders_CartId",
table: "Orders",
column: "CartId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ProductId",
table: "Orders",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ShippingAddressId",
table: "Orders",
column: "ShippingAddressId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "Address");
}
}
}
|
using System;
using System.IO;
namespace Uberware.Study
{
public class MatchingSettings : Settings
{
public bool PlaySounds = true;
public string [] Sounds = new string []
{
"Sounds\\Begin.wav", // 'Begin' sound
"Sounds\\Correct.wav", // 'Correct' sound
"Sounds\\Wrong.wav", // 'Wrong' sound
"Sounds\\Complete.wav", // 'Complete' sound
"Sounds\\Perfect.wav", // 'Perfect' sound
};
public static MatchingSettings FromUserSettings ()
{ return (MatchingSettings)Settings.FromUserSettings(new MatchingSettings()); }
public static MatchingSettings FromFile (string FileName, bool IsUserSettings)
{ return (MatchingSettings)Settings.FromFile(new MatchingSettings(), FileName, IsUserSettings); }
protected override bool LoadSettings (StreamReader file)
{
file.ReadLine();
return true;
}
protected override bool SaveSettings (StreamWriter file)
{
file.WriteLine();
return true;
}
}
}
|
using BHLD.Data.Infrastructure;
using BHLD.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace BHLD.Data.Repositories
{
public interface Ihu_employee_cvRepository : IRepository<hu_employee_cv>
{
IEnumerable<hu_employee_cv> GetAllByEmployee(int tag, int page, int pageSize, out int totalRow);
}
public class hu_employee_cvRepository : RepositoryBase<hu_employee_cv>, Ihu_employee_cvRepository
{
public hu_employee_cvRepository(IDbFactory dbFactory) : base(dbFactory)
{
}
public IEnumerable<hu_employee_cv> GetAllByEmployee(int tag, int page, int pageSize, out int totalRow)
{
throw new NotImplementedException();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bitbrains.AmmyParser
{
public partial class AmmyGrammarAutogeneratorInfo
{
public AmmyGrammarAutogeneratorInfo(string terminalName)
{
var parts = (terminalName + ",,,,").Split(',').Select(a => a.Trim()).ToArray();
TerminalName = parts[0];
CamelTerminalName = GetCamelName(TerminalName);
ClassType = "Ast" + CamelTerminalName;
BaseClass = parts.Length < 2 ? null : parts[1];
if (string.IsNullOrEmpty(BaseClass))
BaseClass = nameof(BbExpressionListNode);
var createClassCommand = parts[2].ToLower();
CreateClass = createClassCommand == "" || createClassCommand == "true";
if (parts[3].Length > 0)
{
Map = parts[3].Split(' ').Select(a => a.Trim())
.Where(a => a.Length > 0)
.Select(int.Parse)
.ToArray();
if (Map.Length == 0)
Map = null;
}
}
private static StringBuilder GetCamelName(string name)
{
var s = new StringBuilder();
var toUpper = true;
foreach (var i in name.Trim())
{
if (i == '_')
{
toUpper = true;
continue;
}
s.Append(toUpper ? char.ToUpper(i) : i);
toUpper = false;
}
return s;
}
public AmmyGrammarAutogeneratorInfo AsAlternative(int index, params string[] elements)
{
Map = new[] {index};
Alternatives = elements;
return this;
}
public AmmyGrammarAutogeneratorInfo AsListOf<T>() => AsListOf(typeof(T).ToString());
public AmmyGrammarAutogeneratorInfo AsListOf(AmmyGrammarAutogeneratorInfo info)
{
if ((info.Alternatives?.Length ?? 0) > 0)
return AsListOf(info.AlternativeInterfaceName);
return AsListOf("object");
}
public AmmyGrammarAutogeneratorInfo AsListOf(string listItemName)
{
// // "using_directives,ExpressionListNode<UsingStatement>",
BaseClass = "ExpressionListNode<" + listItemName + ">";
return this;
}
public AmmyGrammarAutogeneratorInfo AsOneOf(params string[] elements) => AsAlternative(0, elements);
public AmmyGrammarAutogeneratorInfo AsOptional(string baseName = null, string alternativeOf = null)
{
BaseClass = baseName ?? "AstOptNode";
CreateClass = BaseClass != "AstOptNode";
if (!string.IsNullOrEmpty(alternativeOf))
Alternatives = new[] {"Empty", alternativeOf};
return this;
}
public string GetRule()
{
IEnumerable<string> GetAlternatives()
{
if (TerminalName.EndsWith("_opt"))
{
yield return "Empty";
yield return TerminalName.Substring(0, TerminalName.Length - 4);
}
else if (Alternatives != null && Alternatives.Any())
{
foreach (var i in Alternatives)
yield return i;
}
}
if (!string.IsNullOrEmpty(Rule))
return Rule;
var altCode = GetAlternatives().ToArray();
if (altCode.Any()) return string.Join(" | ", altCode);
return null;
}
public AmmyGrammarAutogeneratorInfo Single(params int[] map) => WithMap(0);
public AmmyGrammarAutogeneratorInfo WithMap(params int[] map)
{
if (map != null && map.Length > 0)
Map = map;
return this;
}
private AmmyGrammarAutogeneratorInfo GetList(bool makeRule = false, string separator="null")
{
var el = new AmmyGrammarAutogeneratorInfo(TerminalName + "s").AsListOf(this);
if (makeRule)
el.Rule = $"MakePlusRule({el.TerminalName}, {separator}, {this.TerminalName})";
return el;
}
private AmmyGrammarAutogeneratorInfo GetOptional() =>
new AmmyGrammarAutogeneratorInfo(TerminalName + "_opt").AsOptional();
public StringBuilder CamelTerminalName { get; }
public int[] Map { get; set; }
public bool CreateClass { get; private set; }
public string TerminalName { get; }
public string ClassType { get; }
public string BaseClass { get; set; }
public string EffectiveClassName
{
get { return CreateClass ? ClassType : BaseClass; }
}
public string AlternativeInterfaceName
{
get { return "IAst" + CamelTerminalName; }
}
public string[] Alternatives { get; set; }
public string Rule { get; set; }
public HashSet<string> Punctuations { get; } = new HashSet<string>();
public string Keyword { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TomKlonowski.Model;
namespace TomKlonowski.DB
{
public class TomKlonowskiDbContext : DbContext
{
public TomKlonowskiDbContext()
: base("TomKlonowski")
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<Blog> Blogs { get; set; }
}
}
|
namespace GeneralResources.CursoAlgoritmoEstruturaDeDados.Sorting
{
public class BinaryHeap
{
List<int> _data = new List<int>();
/// <summary>
/// Max-heap
/// </summary>
/// <param name="value"></param>
public void Insert(int value)
{
_data.Add(value);
int i = _data.Count - 1;
int p = Parent(i);
while (IsBigger(_data, i, p))
{
SortUtils.Swap(_data, i, p);
i = p;
p = Parent(i);
}
}
public static void HeapSort(int[] m)
{
Heapify(m, m.Length);
for (int i = m.Length - 1; i >= 0; i--)
{
SortUtils.Swap(m, i, 0);
Heapify(m, i - 1, 0);
}
}
public static BinaryHeap Heapify(IList<int> m, int size)
{
if (size <= 1) return default(BinaryHeap);
//4,2,8,7,1,5,3,6,10
int lastIndex = size - 1;
for (int i = lastIndex / 2 - 1; i >= 0; i--)
{
Heapify(m, size, i);
}
var heap = new BinaryHeap();
heap._data = new List<int>(m);
return heap;
}
public int Dequeue()
{
if (_data.Count == 0) return default(int);
var elem = _data[0];
_data[0] = _data[_data.Count - 1];
_data.RemoveAt(_data.Count - 1);
Heapify(_data, _data.Count, 0);
return elem;
}
static void Heapify(IList<int> m, int size, int index)
{
int biggest = index;
int l = Left(index);
int r = Right(index);
if (l <= size && IsBigger(m, l, biggest))
biggest = l;
if (r < size && IsBigger(m, r, biggest))
biggest = r;
if (biggest != index)
{
SortUtils.Swap(m, biggest, index);
Heapify(m, size, biggest);
}
}
static int Parent(int node)
{
return (node - 1) / 2;
}
static int Left(int node)
{
return 2 * node + 1;
}
static int Right(int node)
{
return 2 * node + 2;
}
static bool IsBigger(IList<int> data, int node1, int node2)
{
return data[node1] > data[node2];
}
[Fact]
public void Validate()
{
//Arrange
var array = new int[] { 4, 2, 8, 7, 1, 5, 3, 6, 10 };
BinaryHeap.HeapSort(array);
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 10 }, array);
//var heap = BinaryHeap.Heapify(array, array.Count());
//Act
//Assert.Equal(10, heap.Dequeue());
//Assert.Equal(8, heap.Dequeue());
//Assert
//Assert.Equal(expected, input);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace otodik_feladat
{
enum BirkaAllapot
{
Halott,
Sérült,
Sértetlen
}
class Birka
{
//Fields and properties
Point pozicio;
public Point Pozicio
{
get
{
return pozicio;
}
private set
{
pozicio = value;
}
}
public BirkaAllapot Allapot { get; private set; }
//Statikus elemek
static Random random;
static Birka()
{
random = new Random();
}
//Konstruktor, ezzel alapból a birka állapota sértetlen és a pozíciójának x és y értéke random 4 és a pályaméretének - 3
public Birka(Size palyaMerete)
{
Allapot = BirkaAllapot.Sértetlen;
Pozicio = new Point(random.Next(4, palyaMerete.Width - 3), random.Next(4, palyaMerete.Height - 3));
}
//Functions and Methods
public bool Loves(Point lovehelye)
{
if (Pozicio == lovehelye)
{
Allapot--;
return true;
}
return false;
}
public void Mozgas()
{
if (Allapot != BirkaAllapot.Halott)
{
bool mozog = (Allapot == BirkaAllapot.Sértetlen) ? random.Next(1, 10) <= 6 : random.Next(1, 10) <= 3;
if (mozog)
{
switch (random.Next(1, 5))
{
case 1:
pozicio.Y--;
//Pozicio = new Point(Pozicio.X, Pozicio.Y - 1);
break;
case 2:
pozicio.X++;
break;
case 3:
pozicio.Y++;
break;
case 4:
pozicio.X--;
break;
}
}
}
}
}
}
|
using UnityEngine;
public class AccessingAParticleSystemModule : MonoBehaviour
{
// Use this for initialization
void Start ()
{
// Get the emission module.
var forceModule = GetComponent<ParticleSystem>().forceOverLifetime;
// Enable it and set a value
forceModule.enabled = true;
forceModule.x = new ParticleSystem.MinMaxCurve(15.0f);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BST_Recursion
{
class Program
{
static void Main(string[] args)
{
BST bst = new BST();
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
bst.InsertRecursively(rand.Next(200));
}
Console.WriteLine("Tree:");
bst.PrintTree();
Console.ReadKey();
}
}
}
|
using Eduhome.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Eduhome.ViewModels
{
public class CourseVM
{
public Caption Caption { get; set; }
public CourseDetails CourseDetails { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Foundry.SourceControl.GitIntegration
{
public class GitSourceObject : ISourceObject
{
public string CommitId { get; set; }
public string TreeId { get; set; }
public string Path { get; set; }
public string Name { get; set; }
public bool IsDirectory { get; set; }
public DateTime DateTime { get; set; }
public string Message { get; set; }
}
} |
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium;
using NUnit.Framework;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
namespace ShortcutsSalon
{
class Program
{
static void Main(string[] args)
{
string []ExceptionVal= new string[10];
FirefoxProfileManager fprofilManager = new FirefoxProfileManager();
FirefoxProfile fprofile = new FirefoxProfile();
//fprofile.SetPreference(
FirefoxDriver driver = new FirefoxDriver(fprofile);
//fprofile.
driver.Navigate().GoToUrl("http://www.shortcuts.com.au/");
driver.FindElement(By.Name("t1")).SendKeys("TestUser");
driver.FindElement(By.Name("t2")).SendKeys("TestCompany");
driver.FindElement(By.Name("t3")).SendKeys("0420727256");
driver.FindElement(By.Name("t4")).SendKeys("testemail@email.com");
driver.FindElement(By.Name("t5")).SendKeys("5050");
IWebElement elementSelect = driver.FindElement(By.Name("t6"));
SelectElement selecElement = new SelectElement(elementSelect);
selecElement.SelectByText("Event");
try
{
if (driver.FindElement(By.LinkText("Home")).Displayed)
{
Console.WriteLine("Home link is displayed");
}
else
{
Console.WriteLine("Home link is not displayed");
ExceptionVal[0] = "No Home link";
}
if (driver.FindElement(By.LinkText("Company")).Displayed)
{
Console.WriteLine("Company link is displayed");
IWebElement CompanyLink = driver.FindElement(By.LinkText("Company"));
Actions builder = new Actions(driver);
//builder.ContextClick(CompanyLink).Perform();
//IJavaScriptExecutor jscript = driver as IJavaScriptExecutor;
//jscript.ExecuteScript("return $(\"a:contains('Company')\").mouseover();");
//driver.FindElement(By.XPath("//div[@id='HeadSubMenu']/a[text()='Contact']")).Click();
//builder.MoveByOffset(5, 5).Perform();
//builder.MoveToElement(CompanyLink).Perform();
//builder.MoveToElement(CompanyLink);
//builder.MoveToElement(CompanyLink).Build().Perform();
//builder.Click(CompanyLink);
//builder.ContextClick(CompanyLink);
//CompanyLink.Click();
}
else
{
Console.WriteLine("Company link is not displayed");
ExceptionVal[1] = "No Company link";
}
if(driver.FindElement(By.LinkText("Products")).Displayed)
{
Console.WriteLine("Products link is displayed");
}
else
{
Console.WriteLine("Products link is not displayed");
}
if (driver.FindElement(By.LinkText("Education")).Displayed)
{
Console.WriteLine("Education Products link is displayed");
}
else
{
Console.WriteLine("Education link is not displayed");
}
if (driver.FindElement(By.LinkText("Support")).Displayed)
{
Console.WriteLine("Support link is displayed");
}
else
{
Console.WriteLine("Support link is not displayed");
}
}
catch(StaleElementReferenceException e)
{
}
Console.ReadLine();
}
}
}
|
using Autofac;
using SomeTask.Modules;
using log4net;
namespace SomeTask
{
public static class Bootstrap
{
private static IContainer Container { get; set; }
public static void Init()
{
var builder = new ContainerBuilder();
builder.RegisterType<TaskManager>().As<ITaskManager>();
builder.RegisterModule(new LoggingModule());
Container = builder.Build();
}
public static ILog GetLogger()
{
using (var scope = Container.BeginLifetimeScope())
{
return scope.Resolve<ILog>();
}
}
public static ITaskManager GetTaskManager()
{
using (var scope = Container.BeginLifetimeScope()) return scope.Resolve<ITaskManager>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rainbow.WorldOverhaul
{
public static class ExplosionPatch
{
public static void SubPatch()
{
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = System.Random;
public class SpawnManager : MonoBehaviour
{
/**
* Variable used to calculate probabilities.
*/
private Random _rand;
/**
* This object holds all the information about the world
*/
private GameStatus _commBus;
/**
* Maximum number of sheep allowed outside of the pen at once
*/
public int maxSheepOutside;
/* ----------------------------------------- */
/* Variables to reference the world entities */
/* ----------------------------------------- */
/* ==== Types of entities ==== */
public Sheep sheepPrefab;
public Wolf wolfPrefab;
public Food [] foodPrefabs;
/* ==== Spawn points for the different entities ==== */
public GameObject [] wolfSpawnPoints;
public GameObject [] sheepEscapePoints;
public GameObject [] foodSpawnPoints;
/**
* Counter to reset the probability once a sheep spawned
*/
private long _sheepTime = 0L;
/**
* Counter to reset the probability once a wolf spawned
*/
private long _wolfTime = 0L;
/* ------------------------------------- */
/* FUNCTIONS TO CALCULATE PROBABILITIES */
/* ------------------------------------- */
/**
* Function that returns the probability at any given time for a wolf to spawn.
*
* Spawns just a wolf iff there are no other wolves and at least 2 sheep
*/
private readonly Func<int, int, double, double> _wolfSpawnThreshold =
(int wolves, int sheep, double time) => (wolves == 0 && sheep >= 2) ? 0 : 101;
/**
* Function that returns the probability at any given time for a sheep to escape the pen.
*/
private readonly Func<int, int, int, double, double> _sheepEscapeThreshold =
(int sheep_out, int sheep_in, int maxOutside, double time) =>
{
if (sheep_out >= maxOutside)
{
return 101;
}
/* We want an exponential function, f(t) = 3^t. To calculate the probability of a sheep escaping, we have
to integrate the function: (3^t)/log(3)
Then, we have to convert it into a value between 0 and 100, being '100' anything bigger than
'maxOutside' */
double prob = 100 - (Math.Pow (5.0, time) / Math.Log (5.0));
return prob > 101? 101 : prob;
}
;
/**
* Spawns all the entities across the map
*/
private void Start ()
{
_rand = new Random ();
/* Discards the first non-random value (yeah... you suck, .NET) */
_rand.Next ();
_commBus = Instances.GetGameStatus ();
/* Adds random food types until all the food points are filled */
foreach (GameObject point in foodSpawnPoints)
{
int idx = _rand.Next (foodPrefabs.Length);
Food foodItem = foodPrefabs[idx];
Instantiate (foodItem, point.transform);
}
StartCoroutine (calcSpawmns ());
}
/**
* Calculates if the determined object should be instantiated randomly at one of the defined points.
*
* <param name="entity">
* Either a <see cref="WolfPrefab"/> or a <see cref="SheepPrefab"/>, which should be created
* </param>
*
* <param name="spawnPoints">
* A list with all the available spawn points.
* </param>
*/
private void _spawnEntity (Entity entity, GameObject [] spawnPoints)
{
double value = _rand.Next (100);
double threshold = 0;
/* It's a different threshold depending on the entity being spawned */
if (entity.GetType () == typeof (Wolf))
{
threshold = _wolfSpawnThreshold (_commBus.wolves, _commBus.sheep_out, _wolfTime);
} else if (entity.GetType () == typeof (Sheep))
{
threshold = _sheepEscapeThreshold (_commBus.sheep_out, _commBus.sheep_in, maxSheepOutside, _sheepTime);
}
if (value < threshold)
{
return;
}
/* Gets a random spawn point. It doesn't matter if the previous entity has already been spawned here, as
they should be walking around and chasing some food */
int idx = _rand.Next (spawnPoints.Length);
GameObject point = spawnPoints [idx];
/* The entity is spawned at one of the predefined points */
if (entity.GetType () == typeof (Sheep))
{
Instantiate (wolfPrefab, point.transform.position, Quaternion.identity);
_wolfTime = 0;
/* Notifies the change */
_commBus.sheepEscaped ();
} else if (entity.GetType () == typeof (Wolf))
{
Instantiate (sheepPrefab, point.transform.position, Quaternion.identity);
_sheepTime = 0;
/* Notifies the change */
_commBus.wolfAdded ();
}
}
/**
* Checks if any spawn event should happen
*/
IEnumerator calcSpawmns ()
{
while (true)
{
yield return new WaitForSeconds (1);
_spawnEntity(wolfPrefab, wolfSpawnPoints);
_spawnEntity(sheepPrefab, sheepEscapePoints);
_sheepTime++;
_wolfTime++;
}
}
/**
* Notifies this <see cref="SpawnManager"/> about a food that has been eaten.
*
* The manager acknowledges the notification and starts a coroutine to spawn a new kind of food.
*
* <param name="position">
* Position of the destroyed food item.
* </param>
*/
public void NotifyFoodEaten (Transform position)
{
StartCoroutine (_spawnFood (position));
}
/**
* Waits a random time between 30 and 90 seconds, and creates a new food item in the designated position.
*
*
* <param name="position">
* Position of the destroyed food item.
* </param>
*/
private IEnumerator _spawnFood (Transform position)
{
while (true)
{
yield return new WaitForSeconds(_rand.Next(30, 90));
int idx = _rand.Next(foodPrefabs.Length);
Food newItem = foodPrefabs[idx];
Instantiate(newItem, position);
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
namespace SC.Models
{
[Table("UserShoppingCart")]
public class ShoppingCart
{
public int UserId { get; set; }
public int ProductId { get; set; }
public User User { get; set; }
public Product Product { get; set; }
public decimal Quantity { get; set; }
}
}
|
using System.Web.UI;
namespace mssngrrr
{
public partial class Main : MasterPage
{
}
} |
namespace WindowsFA
{
using System;
/// <summary>
/// Summary description for MoveInfo.
/// </summary>
public class MoveInfo
{
public double fxMove; // Fraction to move at each compass point:X
public double fyMove; // Y
public double fMagnify; // Fraction to grow or shrink at each compass point (X and Y)
public MoveInfo()
{
}
public void setMoveInfo(double fNewXMove, double fNewYMove, double fNewMagnify)
{
fxMove = fNewXMove;
fyMove = fNewYMove;
fMagnify = fNewMagnify;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{
private Transform playertf;
[Range(0.0f, 10.0f)] public float walkingspeed = 1.0f;
[Range(0.0f, 10.0f)] public float strafingspeed = 0.4f;
[Range(0.0f, 10.0f)] public float rotationspeed = 5.0f;
[SerializeField] AudioSource step1, step2, step3, step4;
private float audiotimer = 0.0f;
private byte laststepfxplayed = 4;
[SerializeField] GameObject startingArea;
[SerializeField] DialogueSystem dialogueSystem;
void Start()
{
playertf = gameObject.transform;
audiotimer = Time.timeSinceLevelLoad;
}
void Update()
{
playertf.Translate(new Vector3(Input.GetAxis("Vertical") * walkingspeed, 0, Input.GetAxis("Horizontal") * -1.0f * strafingspeed));
playertf.Rotate(0, Input.GetAxis("Mouse X") * rotationspeed, 0, Space.Self);
if ((Input.GetAxis("Vertical") > 0.45f || Input.GetAxis("Horizontal") > 0.35f) && (Time.timeSinceLevelLoad - audiotimer > 0.33f))
{
switch (laststepfxplayed)
{
case 1:
step2.Play();
laststepfxplayed = 2;
break;
case 2:
step3.Play();
laststepfxplayed = 3;
break;
case 3:
step4.Play();
laststepfxplayed = 4;
break;
case 4:
step1.Play();
laststepfxplayed = 1;
break;
default:
break;
}
audiotimer = Time.timeSinceLevelLoad;
}
}
private void OnTriggerExit(Collider triggerArea)
{
if (triggerArea.gameObject == startingArea)
{
dialogueSystem.HideInstructions();
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TodoApp.Models;
namespace TodoApp.Data
{
public class Connection : DbContext
{
public Connection(DbContextOptions<Connection> options)
: base(options)
{
}
public DbSet<USER> USER { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<USER>(eb => {
eb.ToTable("USER");
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClaimDi.DataAccess.Entity
{
public class MappingCarTaskBike
{
public Guid Id { get; set; }
public Guid AccId { get; set; }
public int? CarId { get; set; }
public virtual CarInfo CarInfo { get; set; }
public string TaskId { get; set; }
public DateTime? CreateDate { get; set; }
public string CreateBy { get; set; }
}
public class MappingCarTaskBikeConfig : EntityTypeConfiguration<MappingCarTaskBike>
{
public MappingCarTaskBikeConfig()
{
ToTable("MappingCarTaskBike");
Property(t => t.Id).HasColumnName("id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(t => t.AccId).HasColumnName("acc_id");
Property(t => t.CarId).HasColumnName("car_id");
Property(t => t.TaskId).HasColumnName("task_id");
Property(t => t.CreateDate).HasColumnName("create_date");
Property(t => t.CreateBy).HasColumnName("create_by");
HasOptional(t => t.CarInfo).WithMany().HasForeignKey(t => t.CarId);
HasKey(t => t.Id);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DraggableBoxScript : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
GetComponent<Rigidbody2D>().mass = 100;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
GetComponent<Rigidbody2D>().mass = 5;
}
}
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
GetComponent<Rigidbody2D>().mass = 100;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class AdminHome : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("New_problem.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["ADMIN"] = "";
Response.Redirect("Default.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("CreateAccount.aspx");
}
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect("Delete.aspx");
}
protected void Button5_Click(object sender, EventArgs e)
{
Response.Redirect("Edit Problem.aspx");
}
protected void Button6_Click(object sender, EventArgs e)
{
Response.Redirect("CheckRequest.aspx");
}
} |
namespace MyWebServer.Enums
{
public enum HeaderType
{
HttpRequiest,HttpResponse
}
} |
using UnityEngine;
using System.Collections;
using CSSynth.Midi;
using System.Collections.Generic;
public class MidiParser : MonoBehaviour {
/// <summary>
/// Parse notes from midi data, combine all note event in specified tracks into one array
/// </summary>
/// <param name="midiData">Raw midi data</param>
/// <param name="levelData">Result holder</param>
/// <param name="tracksToParse">If null, will parse from all available track, else, only process specified tracks</param>
/// <returns></returns>
public static int ParseNotesData(byte[] midiData, ref MidiData levelData, List<int> tracksToParse = null) {
int res = 0;
//load up midi data
MidiFile songFile = new MidiFile(midiData);
//Look for Denominator first, before touching BPM or MicroSecondsPerQuarterNote
var timesignatureEvents = songFile.getAllMidiEventsofType(MidiHelper.MidiChannelEvent.None, MidiHelper.MidiMetaEvent.Time_Signature);
if (timesignatureEvents.Count > 0) {
songFile.Denominator = (byte)timesignatureEvents[0].Parameters[1];
}
else {
//default of midi without time_signature value
songFile.Denominator = 2;
}
//set Tempo for this file, this value will depends on Denominator above
var tempoEvents = songFile.getAllMidiEventsofType(MidiHelper.MidiChannelEvent.None, MidiHelper.MidiMetaEvent.Tempo);
if (tempoEvents.Count > 0) {
songFile.MicroSecondsPerQuarterNote = (uint)tempoEvents[0].Parameters[0];
}
//update levelData bpm
levelData.beatsPerMinute = songFile.BeatsPerMinute;
levelData.denominator = (int)songFile.Denominator;
levelData.deltaTickPerQuarterNote = songFile.MidiHeader.deltaTicksPerQuarterNote;
levelData.notesData = new Dictionary<int, List<NoteData>>(16);
//prepare to calculate timing of each note event
float secondsPerPulse = (float)songFile.MicroSecondsPerQuarterNote / 1000000 / (float)songFile.MidiHeader.deltaTicksPerQuarterNote;
//start parsing from track 1, since track 0 is mostly meta events
for (int i = 0; i < songFile.Tracks.Length; i++) {
//Debug.Log("Processing track " + i);
//only parse specified track if required
if (tracksToParse != null && !tracksToParse.Contains(i)) { continue; }
MidiEvent[] midiEvents = songFile.Tracks[i].midiEvents;
//list of notes this track contains
List<NoteData> notesList = new List<NoteData>(100);
//prepare place to store note's timing
Dictionary<byte, Stack<MidiEvent>> notesArray = new Dictionary<byte, Stack<MidiEvent>>();
for (int j = 0; j < midiEvents.Length; j++) {
if (midiEvents[j].isChannelEvent()) {
MidiEvent evt = midiEvents[j];
byte note = evt.parameter1;
//check for event's type, if is note_on push into timing table
if (evt.midiChannelEvent == MidiHelper.MidiChannelEvent.Note_On) {
if (notesArray.ContainsKey(note)) {
notesArray[note].Push(evt);
}
else {
Stack<MidiEvent> noteTiming = new Stack<MidiEvent>();
noteTiming.Push(evt);
notesArray.Add(note, noteTiming);
}
//print("--Added note " + note+ " into array");
}//if is note_off, calculate note duration and add to song data
else if (evt.midiChannelEvent == MidiHelper.MidiChannelEvent.Note_Off) {
MidiEvent onEvt = notesArray[note].Pop();
//when to be displayed
float noteTime = onEvt.deltaTimeFromStart * secondsPerPulse;
//how long the note should be displayed
float noteDuration = (evt.deltaTimeFromStart - onEvt.deltaTimeFromStart);
NoteData n = new NoteData();
n.durationInTick = (int)noteDuration;
n.tickAppear = (int) onEvt.deltaTimeFromStart;
noteDuration = (noteDuration > 0) ? noteDuration * secondsPerPulse : 0;
n.duration = noteDuration;
n.volume = onEvt.parameter2 / 127.0f;
//print("Volume for note = " + n.volume);
n.nodeID = note;
n.timeAppear = noteTime;
notesList.Add(n);
//Debug.Log("Added note: " + note);
}
}
}
//add to level data
levelData.notesData.Add(i, notesList);
}
return res;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SimpleTaskListSPA.Data;
using SimpleTaskListSPA.Data.DTO;
using SimpleTaskListSPA.Models;
using SimpleTaskListSPA.Models.Repo;
namespace SimpleTaskListSPA.Controllers
{
public class TaskItemController : BaseController
{
private readonly ITaskItemRepo _repo;
public TaskItemController(ITaskItemRepo repo)
{
_repo = repo;
}
[HttpGet("task/{id}")]
public async Task<TaskItem> GetTaskAsync(long id)
{
TaskItem task = await _repo.GetTaskAsync(id);
return task;
}
[HttpPost("tasks")]
public async Task<TaskItemResponse> ReceiveTasksAsync([FromBody] QueryOptions options)
{
TaskItemResponse tasks;
try
{
tasks = await _repo.ReceiveTasksAsync(options);
}
catch (Exception)
{
tasks = null;
}
return tasks;
}
[HttpPost("create")]
public async Task<ActionResult> CreateTaskAsync([FromBody] TaskItem task)
{
task = SetCreationAndEffectiveDates(task);
return await CreateAsync(task, _repo.AddAsync);
}
[HttpPut("update")]
public async Task<ActionResult> UpdateTaskAsync([FromBody] TaskItem task)
{
task = SetCreationAndEffectiveDates(task);
return await UpdateAsync(task, _repo.UpdateAsync);
}
[HttpPut("setdate")]
public async Task<ActionResult> SetTaskDateAsync([FromBody] TaskDates taskDates)
{
TaskItem task;
task = SetPlanningDate(taskDates);
task = SetCreationAndEffectiveDates(task);
return await UpdateAsync(task, _repo.UpdateAsync);
}
[HttpDelete("delete")]
public async Task<ActionResult> DeleteTaskAsync([FromBody] TaskItem task)
{
return await DeleteAsync(task, _repo.DeleteAsync);
}
private TaskItem SetPlanningDate(TaskDates taskDates)
{
TaskItem task = taskDates.TaskItem;
int days = taskDates.DaysAdditionToPlannigDate;
switch (days)
{
case 0:
task.PlanningDate = DateTime.Today;
break;
case 1:
task.PlanningDate = DateTime.Today.AddDays(1);
break;
default:
task.PlanningDate = null;
break;
}
return task;
}
private TaskItem SetCreationAndEffectiveDates(TaskItem taskItem)
{
if (taskItem.CreationDate == null)
{
taskItem.CreationDate = DateTime.Today;
}
if (taskItem.IsCompleted && taskItem.EffectiveDate == null)
{
taskItem.EffectiveDate = DateTime.Today;
}
else if (!taskItem.IsCompleted && taskItem.EffectiveDate.HasValue)
{
taskItem.EffectiveDate = null;
}
return taskItem;
}
}
}
|
using System;
using System.Net;
using System.Reflection;
namespace GFPApiExamples.ApiTesters
{
public class PhotosApiTester : ApiTester
{
public int GetPhoto(int photoId)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(GetUrl("Photos/" + photoId));
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json";
request.Headers.Add("Authorization", string.Format("api-key {0}", ApiKey));
using (var response = (HttpWebResponse)request.GetResponse())
{
return (int)response.StatusCode;
}
}
catch (WebException ex)
{
var response = (HttpWebResponse)ex.Response;
if (response != null)
return (int)response.StatusCode;
return 0;
}
}
public int GetPhotos()
{
try
{
var request = (HttpWebRequest) WebRequest.Create(GetUrl("Photos"));
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json";
request.Headers.Add("Authorization", string.Format("api-key {0}", ApiKey));
using (var response = (HttpWebResponse) request.GetResponse())
{
return (int) response.StatusCode;
}
}
catch (WebException ex)
{
var response = (HttpWebResponse) ex.Response;
if (response != null)
return (int) response.StatusCode;
return 0;
}
}
public int PutLowResImage(int photoId)
{
try
{
var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
var request = (HttpWebRequest) WebRequest.Create(GetUrl("Photos/" + photoId + "/LowResImage"));
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "PUT";
request.KeepAlive = true;
request.Headers.Add("Authorization", string.Format("api-key {0}", ApiKey));
using (var requestStream = request.GetRequestStream())
{
var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
var header = string.Format("Content-Disposition: form-data; name=\"Image\"; filename=\"LowResImage.jpg\"\r\n Content-Type: application/octet-stream\r\n\r\n");
var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(headerbytes, 0, headerbytes.Length);
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("GFPApiExamples.LowResExample.jpg"))
{
var buffer = new byte[1024];
var bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
}
requestStream.Close();
using (var response = (HttpWebResponse) request.GetResponse())
{
return (int) response.StatusCode;
}
}
}
catch (WebException ex)
{
var response = (HttpWebResponse)ex.Response;
if (response != null)
return (int)response.StatusCode;
return 0;
}
}
public int PutHighResImage(int photoId)
{
try
{
var boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
var request = (HttpWebRequest)WebRequest.Create(GetUrl("Photos/" + photoId + "/HighResImage"));
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "PUT";
request.KeepAlive = true;
request.Headers.Add("Authorization", string.Format("api-key {0}", ApiKey));
using (var requestStream = request.GetRequestStream())
{
var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
var header = string.Format("Content-Disposition: form-data; name=\"Image\"; filename=\"HighResImage.jpg\"\r\n Content-Type: application/octet-stream\r\n\r\n");
var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(headerbytes, 0, headerbytes.Length);
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("GFPApiExamples.HighResExample.jpg"))
{
var buffer = new byte[1024];
var bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
}
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return (int)response.StatusCode;
}
}
}
catch (WebException ex)
{
var response = (HttpWebResponse)ex.Response;
if (response != null)
return (int)response.StatusCode;
return 0;
}
}
private string GetUrl(string path)
{
return ServerHost.TrimEnd('/').TrimEnd('\\') + "/" + path;
}
}
} |
using System.Collections.Generic;
using System.Globalization;
namespace Eda.Integrations.Delivery.SpsrExpress
{
public class SpsrExpressDeliveryServiceFactory : IDeliveryServiceFactory
{
public IAddress NewAddress(string postalCode, IStreet street, string building, IContact contact, string note)
{
throw new System.NotImplementedException();
}
public IStreet NewSreet(object id, ICity city, string name, double latittude, double longitude)
{
throw new System.NotImplementedException();
}
public ICity NewCity(object id, IRegion region, IReadOnlyDictionary<CultureInfo, string> names, double latitude, double longitude)
{
throw new System.NotImplementedException();
}
public IRegion NewRegion(object id, ICountry country, IReadOnlyDictionary<CultureInfo, string> names)
{
throw new System.NotImplementedException();
}
public ICountry NewCountry(object id, IReadOnlyDictionary<CultureInfo, string> names, CultureInfo culture, object currency)
{
throw new System.NotImplementedException();
}
public IContact NewContact(string name, string phone, string email) =>
new SpsrExpressContact(name, phone, email);
public IDeliveryRequest NewDeliveryRequest(IAddress sourceAddress, IAddress destinationAddress, object deliveryType,
IParcel parcel, object currency)
{
throw new System.NotImplementedException();
}
public IDeliveryInformation NewDeliveryInformation(IDeliveryRequest request, decimal cost)
{
throw new System.NotImplementedException();
}
public IDelivery NewDelivery(object id, decimal cost, object currency, string type, IAddress source, IAddress destination,
IPickPoint pickPoint, IParcel parcel)
{
throw new System.NotImplementedException();
}
public IPickPoint NewPickupPoint(object id, IAddress address, WorkingWeekSchedule schedule)
{
throw new System.NotImplementedException();
}
public IParcel NewParcel(decimal weight, object parcelType, int width, int height, int length)
{
throw new System.NotImplementedException();
}
public IDeliveryOrder NewDeliveryOrder(object id, IDelivery delivery)
{
throw new System.NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_Currency_Converter
{
public partial class CurrencyConverter : Form
{
public CurrencyConverter()
{
InitializeComponent();
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void NumericUpDown_ValueChanged(object sender, EventArgs e)
{
decimal bgn = this.numericUpDown.Value;
decimal eur = bgn / 1.95583m;
this.labelResult.Text = bgn + " BGN = " + Math.Round(eur,2) + " EUR";
}
private void LabelResult_Click(object sender, EventArgs e)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireSwordAttackFx : SwordAttackFx
{
}
|
namespace PFRCenterGlobal.Models
{
public class SessionModel
{
public string Id { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Script that holds project path for image/prefab
/// </summary>
public class UILocation : MonoBehaviour {
// Images
public static readonly string _large_color_maps = "Genuage/Unity/Textures/ColorMaps/large/";
public static readonly string _thin_color_maps = "Genuage/Unity/Textures/ColorMaps/thin/";
public static readonly string _large_color_rotated = "Genuage/Unity/Textures/ColorMaps/rotated/";
public static readonly string _visp_logo = "Genuage/Unity/Textures/logo/visp_logo";
// Prefab
public static readonly string _input_label = "Genuage/Prefabs/UI/InputLabel";
public static readonly string _slider = "Genuage/Prefabs/UI/Slider";
public static readonly string _scroll_view = "Genuage/Prefabs/UI/Scroll View";
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CoreTest1.Models.MyViewModel
{
public class PositionData
{
public int EmployeeID { get; set; }
public bool Assigned { get; set; }
public string Name { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace RctByTN.Model
{
public abstract class ParkElement
{
protected Int32 x;
protected Int32 y;
protected Int32 buildCost;
protected Int32 maintainCost;
protected Int32 areaSize;
protected ElementStatus status;
public int X { get => x; set => x = value; }
public int Y { get => y; set => y = value; }
public int BuildCost { get => buildCost; set => buildCost = value < 0 ? 0 : value; }
public int MaintainCost { get => maintainCost; set => maintainCost = value < 0 ? 0 : value; }
public ElementStatus Status { get => status; set => status = value; }
public int AreaSize { get => areaSize; set => areaSize = value; }
public ParkElement(Int32 x, Int32 y, Int32 buildcost, Int32 maintainCost)
{
this.X = x;
this.Y = y;
this.BuildCost = buildcost;
this.MaintainCost = maintainCost;
this.Status = ElementStatus.InBuild;
this.AreaSize = 1;
}
public abstract void ModifyGuest(Guest guest);
}
}
|
using System;
using System.Security.Cryptography;
using System.Net;
using System.Web.Mvc;
using Modelos;
using Servicos;
using System.Web.Security;
using System.Text;
using System.IO;
namespace WEBTeste.Controllers
{
public class UsuarioController : Controller
{
UsuarioServico serv = new UsuarioServico();
private const string initVector = "r5dm5fgm24mfhfku";
private const string passPhrase = "yourpassphrase";
private const int keysize = 256;
// GET: Usuario
[Authorize]
public ActionResult Index()
{
return View(serv.ObterUsuarios());
}
// GET: Usuario/Details/5
[Authorize]
public ActionResult Details(int? Pid)
{
if (Pid == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Usuario usuario = serv.ObterUsuario(Pid.Value);
if (usuario == null)
{
return HttpNotFound();
}
return View(usuario);
}
// GET: Usuario/Create
public ActionResult Create()
{
return View();
}
// POST: Usuario/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,nmUsuario,dsEmail,dsSenha")] Usuario usuario)
{
if (ModelState.IsValid)
{
usuario.dsSenha = Encrypt(usuario.dsSenha);
serv.IncluirUsuario(usuario);
if (!User.Identity.IsAuthenticated)
{
return Login(usuario.dsEmail, usuario.dsSenha);
}
return RedirectToAction("Index");
}
return View(usuario);
}
// GET: Usuario/Edit/5
[Authorize]
public ActionResult Edit(int? Pid)
{
if (Pid == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Usuario usuario = serv.ObterUsuario(Pid.Value);
if (usuario == null)
{
return HttpNotFound();
}
usuario.dsSenha = Decrypt(usuario.dsSenha);
return View(usuario);
}
// POST: Usuario/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,nmUsuario,dsEmail,dsSenha")] Usuario usuario)
{
if (ModelState.IsValid)
{
usuario.dsSenha = Encrypt(usuario.dsSenha);
serv.AtualizarUsuario(usuario);
return RedirectToAction("Index");
}
return View(usuario);
}
// GET: Usuario/Delete/5
[Authorize]
public ActionResult Delete(int? Pid)
{
if (Pid == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Usuario usuario = serv.ObterUsuario(Pid.Value);
if (usuario == null)
{
return HttpNotFound();
}
return View(usuario);
}
// POST: Usuario/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int Pid)
{
Usuario usuario = serv.ObterUsuario(Pid);
serv.ExcluirUsuario(usuario);
return RedirectToAction("Index");
}
[AllowAnonymous]
public ActionResult Login()
{
ViewBag.ReturnUrl = Request.QueryString["ReturnUrl"];
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult Login(string Pemail, string Psenha)
{
try
{
Usuario usuario = serv.RealizarLogin(Pemail, Encrypt(Psenha));
if (usuario != null)
{
FormsAuthentication.SetAuthCookie(usuario.nmUsuario, false);
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl != null)
return Redirect(returnUrl);
else
return RedirectToAction("Index", "Home");
}
ViewBag.Message = "Email e/ou senha inválidos";
return View();
}
catch (Exception ex)
{
ViewBag.Message = ex.Message.ToString();
return View();
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
public static string Encrypt(string senha)
{
if (senha == "" || senha == null)
{
return "";
}
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(senha);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
public static string Decrypt(string senha)
{
if (senha == "" || senha == null)
{
return "";
}
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(senha);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*
HorzBar
+----------+
VertBar
|
|
|
|
|
Frame
+------+
|
|
|
+------+
Ladder
+------+
|
|
|
+------+
|
|
|
+------+
|
|
|
+------+
*/
namespace Bars
{
class Program
{
static void Main(string[] args)
{
HorzBar h1 = new HorzBar(5);
Console.WriteLine("Latimea barei orizontale este: {0}", h1.Width);
VertBar v1 = new VertBar(3);
Console.WriteLine("Inaltimea barei verticale este: {0}", v1.Height);
Frame f1 = new Frame(10, 8);
Console.WriteLine("Latimea frame-ului f1 este: {0}", f1.Width);
Console.WriteLine("Inaltimea frame-ului f1 este: {0}", f1.Height);
Ladder l = new Ladder(6, 4);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication1.Models;
using WebGrease.Css.Extensions;
namespace WebApplication1.Controllers
{
public class CouponsController : ApiController
{
// GET: api/Coupons
public IEnumerable<Coupon> Get()
{
var selectString = string.Format(ItemsController.select + " Where ItemId in ({0})", "'CPNMILITITARY','CPNFSG','CPNFSR','CPNBKCG','CPNBKCR','CPNBOWCLUB','CPNBOWR','CPNTEXT'");
var coupons = SharedDb.PosimDb.GetMany<Coupon>(selectString).ToList();
coupons.Add(new Coupon
{
Description = "Memorial Day Sale",
ItemID = "memsale2014",
DiscountPercent = .3f,
TransCode = "S",
StartDate = DateTime.Today,
EndDate = new DateTime(2014,5,26),
SelectedItemsOnly = true,
});
coupons.ForEach(x =>
{
float percent;
bool isManual;
if(float.TryParse(x.Misc1, out percent))
x.DiscountPercent = percent;
else if (bool.TryParse(x.Misc1, out isManual))
x.ManualDiscount = isManual;
});
return coupons;
}
// GET: api/Coupons/5
public string Get(int id)
{
return "value";
}
// POST: api/Coupons
public void Post([FromBody]string value)
{
}
// PUT: api/Coupons/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Coupons/5
public void Delete(int id)
{
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.